Reputation: 101
I'm a beginner in JS. I'm writing a method that receives an input array and needs to check if it is empty. My first approach was using array === []
as a condition in the if statement inside the method, but it didn't work. It works when I write the condition array.length === 0
. I thought they had the same meaning. Can someone explain why the former is not working?
Thanks in advance.
Upvotes: 1
Views: 10385
Reputation: 1211
Because array === []
is comparing if two objects are identical. And in JS two objects are identical when the two are exactly same. And the only way to check if two objects are exactly same is if they occupy the same space in memory.
And how do we do that? we check if both objects point to the same memory address. In other programming languages they call this memory address a pointer.
Because []
is creating an object on the fly it is a new object so the comparison returns false.
On the other hand array.length === 0
is comparing to primitive values (numbers) and in JS if two primitive values have the same content they are equal so it returns true.
Upvotes: 4
Reputation: 14101
The first check: array === []
checks if both arrays are of the same type (check) and if they are the same array.
The reason the result is false is because:
array
is stored in location A, and []
is stored somewhere else.This is caused by how javascript works with arrays and objects: javascript does not check content, it only checks whether they point to the same array or object in memory. That is why you have to use the second option.
More detailed examples:
// for strings and numbers, javascript checks CONTENT
let a = 'Bill';
let b = 'Bill';
console.log(a === b); // TRUE
// for arrays and objects, javascript checks POINTERS
let a = ['Bill'];
let b = ['Bill'];
console.log(a === b); // FALSE
// also:
var a = ['Bill'];
var b = a;
console.log(a === b); // TRUE
a = ['Joe'];
console.log(a === b); // TRUE
console.log(b); // 'Joe'
Upvotes: 0
Reputation: 413966
The comparison
if (array === [])
compares the identity of two objects. One object is never equal to (the same as) another, different object, at least in the sense that "equality" is defined in JavaScript. Object comparisons in JavaScript are always just a test to see whether some expression refers to some particular known object or not. The comparisons do not "look inside" the compared objects.
One perhaps non-obvious detail is that the expression []
is not a reference to some global, conceptual "the empty array"; it is a request to create a brand new empty array. Thus it's also the case that the comparison
if ([] === [])
will be false, because on both sides of the ===
operator a new, distinct array is created.
Upvotes: 8