Home > Mobile >  what does -1 represent in js?
what does -1 represent in js?

Time:12-28

function first(first, second) {
    return Array.prototype.every.call(first, function(c) {
        return second.indexOf(c) > -1;
    }, this);
}

everything works perfectly, but I don't really understand what ".indexOf(c) > -1" is in the function

CodePudding user response:

Because if indexof equal -1 it means that the element c doesn't exist in the array named "second". So basically if the element "c" exist in that array it will return the index of that element which is bigger than -1 which make that statement true.

CodePudding user response:

Method returns true if in array called second, exists element from array first.

According to the documentation

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present

So here, we are checking if in array callend second element first exists, by exists we are expecting it has an array index greater than zero. If it has a negative value then it does not exist in the array. With examples:

const second = [1,4,5];
first([1], second) // returns true (value 1 has index === 0)
first([5], second) // returns true (value 5 has index === 2)
first([7], second) // returns false (index===-1) - value 7 does not belong in this array
  • Related