DEV Community

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

Posted on • Edited on

1 1

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


Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay