I guess your question is why when the array is empty it does not meet the condition arr === []
.
In javascript there are the types of values "primitive" or "types by value". This implies that these values are immutable and that when the value of a variable with a "primitive value" is accessed, the value is accessed directly. In this way, if two variables have the primitive value 3
and are compared, they will be equal since their values are the same:
var a = 3;
var b = 3;
var c = 4;
console.log('a y b tienen el valor 3 y son iguales:', a===b);
console.log('a y c tienen diferentes valores y son diferentes:', a===c);
All other types are objects or "types by reference". These values can be modified (you can add properties or methods, change the values of the properties, add or change elements of an array ...) and the variables what they contain is a reference to the object. In this way when comparing two variables with objects the values that are compared are the references (pointers) to the objects, that is, two variables will be the same if they have references to the same object, not if they refer to two identical objects:
var a = { prop: 4 };
var b = { prop: 4 };
var c = a;
console.log('a y b hacen referencia a diferentes objetos:', a===b);
console.log('a y c hacen referencia al mismo objeto: ', a===c);
We can see the difference if we change the value of the prop
property of the current example in each of the objects:
var a = { prop: 4 };
var b = { prop: 4 };
var c = a;
console.log('a y b hacen referencia a diferentes objetos:', a===b);
console.log('a y c hacen referencia al mismo objeto: ', a===c);
a.prop = 5;
console.log('a.prop ahora es 5:', a.prop);
console.log('c.prop también es 5:', c.prop);
console.log('b hace referencia a otro objeto por lo que b.prop sigue siendo 4:', b.prop);
The same thing happens with arrays:
var a = [];
var b = [];
var c = a;
console.log('a y b hacen referencia a diferentes arrays (aunque los dos estén vacíos):', a===b);
console.log('a y c hacen referencia al mismo array: ', a===c);
I hope I have clarified it a bit.