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


SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay