I was very surprised to find out that:
> 'a' in ['a', 'b']
false
> ['a','b'].includes('a')
true
What does each command perform in NodeJS?
I was very surprised to find out that:
> 'a' in ['a', 'b']
false
> ['a','b'].includes('a')
true
What does each command perform in NodeJS?
This is not node specific but ECMA (JS) specific.
in
OperatorChecks the existence of key in the collection (similar to hasOwnProperty
but also check inherited keys in prototype chain)
includes
method of Array (introduced in ES6)Checks the existence of value in the collection
Array.includes()
checks for the existence of a certain value in an array, while the in
operator checks for the existence of a key in an object (or an index in the case of arrays like you're describing).
console.log('a' in ['a', 'b']); // false, no such key
console.log(0 in ['a', 'b']); // true, 0 is a key that exists
console.log(1 in ['a', 'b']); // true, 1 is a key that exists
console.log(2 in ['a', 'b']); // false, 2 is a key that doesn't exists