dhunmoon
dhunmoon

Reputation: 71

JavaScript arr.every() method?

I was looking into Javascript .every documentation and it have a second parameter which is passed the description says

Optional. Value to use as this when executing the callback. If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function.

which means that I can access that values as this in the callback function, what is a practical example of this?

Upvotes: 0

Views: 180

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386620

Every iteration method of Array contains thisArg as second parameter. This is an example for filtering object keys with another object by using a prototype, which usually requires an object, which is handed over as argument, or in the second a bound to the method.

var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
    secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };

function intersection(o1, o2) {
    return Object.keys(o1).filter(Object.prototype.hasOwnProperty, o2);
}

console.log(intersection(firstObject, secondObject));

The same with previously bound o2.

var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
    secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };

function intersection(o1, o2) {
    return Object.keys(o1).filter(Object.prototype.hasOwnProperty.bind(o2));
}

console.log(intersection(firstObject, secondObject));

Upvotes: 2

Rayon
Rayon

Reputation: 36599

As per MDN,

Optional. Value to use as this when executing callback. [Ref]

It means, you can use provided value as this in callback function to test the value.

const data = [0, 1, 2, 3];
const doesPass = data.every(function(el) {
  return el < this.toTest;
}, {
  toTest: 4
});
console.log(doesPass);

Upvotes: 4

Related Questions