I am working on a part of the code where I have an array which looks like [[data]]
. The data
is rendered on the server side through the Django temp
Because Arrays are reference type, meaning, if for example you make an array
let a = [1,2,3,4,5];
let b = a;
the b is actually just a reference of array a, so if you compare them
a===b is true,
because they are basically link together.. So if you change something to array b it will also going to be change to array a,
b[0] = "test";
array a now is ["test",2,3,4,5];
But if you do this this
let a = [1,2,3,4,5];
let b = a.slice(0);
and then compare them
a===b is false
because now they are both different Arrays, meaning if you change the Array b, it will not affect the Array a
b[0] ="hello";
Array a is still [1,2,3,4,5]
while array b is now ["hello",2,3,4,5]
that is also what happen when you compare the []===[] is false
Because basically what you are asking to JavaScript is if they are the same Array which is not
Because they are different instances of an Array, thus not equal.
Javascript is like Java in that the ==
operator compares the values of primitive types, but the references of objects. You're creating two arrays, and the ==
operator is telling you that they do not point to the same exact object in memory:
var b = new Array( 1, 2, 3 );
var c = new Array( 1, 2, 3 );
console.log(b == c); // Prints false.
console.log(b == b); // Prints true.
console.log(b === c); // Prints false.
b = c;
console.log(b == c); // Now prints true.
You have to do a deep comparison by hand if you want to compare the values of the objects.
Because ==
(and ===
) test to see if two objects are the same object and not if they are identical objects.
Most test frameworks will include functions such as deepEqual if you want to see if two objects are identical.
The expression [] == []
has an equivalent notation of:
new Array() == new Array()
And knowing that Array
is also an Object
, the behaviour of the comparison is unambiguously explained in The Abstract Equality Comparison Algorithm section of the ECMAScript Language Specification:
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
Your comparison result is explained by 1.6
, highlighted above.
Alternative expression
In your case I would suggest to simply use this condition instead:
if (a[0].length == 0) {
console.log('no data');
}
Because []
creates a new array, so you are comparing one array object with another array object.
It's not the contents of the arrays that is compared, the object references are compared. They are not equal because it's not the same object instance.