DEV Community

Cover image for JavaScript isArray and thisArg Methods
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript isArray and thisArg Methods

s-l1600.jpg


isArray method

The typeof method does not distinguish between arrays and objects.

See the example below:

console.log( typeof {} ); // object
console.log( typeof [] ); // object
Enter fullscreen mode Exit fullscreen mode

The isArray method returns true if it is an array, false otherwise.

The syntax is shown below:

Array.isArray(arr);
Enter fullscreen mode Exit fullscreen mode

See the example below:

console.log( Array.isArray({}) ); // false
console.log( Array.isArray([]) ); // true
Enter fullscreen mode Exit fullscreen mode

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]);
// ...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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


image.png


Top comments (0)