isArray method
The typeof
method does not distinguish between arrays and objects.
See the example below:
console.log( typeof {} ); // object
console.log( typeof [] ); // object
The isArray
method returns true if it is an array, false otherwise.
The syntax is shown below:
Array.isArray(arr);
See the example below:
console.log( Array.isArray({}) ); // false
console.log( Array.isArray([]) ); // true
thisArg method
Most array methods (find
filter
map
...) have the thisArg
has an argument.
See the syntax below:
array.find(func[, thisArg]);
array.filter(func[, thisArg]);
array.map(func[, thisArg]);
// ...
thisArg
is rarely used and optional.
See the example below:
const army = {
minAge: 18,
maxAge: 27,
canJoin(user) {
return user.age >= this.minAge && user.age < this.maxAge;
}
};
const users = [
{ age: 16 },
{ age: 20 },
{ age: 23 },
{ age: 30 }
];
// find users, for who army.canJoin returns true
let soldiers = users.filter(army.canJoin, army); // between 18 and 26
// => { age: 20 }, { age: 23 },
console.log(soldiers.length); // 2
console.log(soldiers[0].age); // 20
console.log(soldiers[1].age); // 23
A call to users.filter(army.canJoin, army)
can be replaced with users.filter(user => army.canJoin(user))
are the same. Most people prefer the latter because itis easier to understand.
Happy coding