Why is [] !== [] in JavaScript? [duplicate] - javascript

This question already has answers here:
Why isn't [1,2,3] equal to itself in Javascript? [duplicate]
(6 answers)
Closed 4 years ago.
Why is [] !== [] in JavaScript?
I read through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness but I could not find anything that explains this.
Edit:
I don't think this question or this question is an exact duplicate of mine. It asks about the == operator which just behaves crazy. The answer is an answer to my question but it's not the same question.

That does a reference check on the two array literals to see if they are the same instance. The fact that you have two literals means that you are constructing two separate arrays, therefore the reference check returns false. This would return true:
var a = []
var b = a
//b === a
This is because we have two references to the same array.

[] creates a new (and empty) array each time you write it. You are comparing two arrays, regardless of their content, their pointer (or reference) are being compared.
var array = [];
var anotherArray = array; // these two will point to the same array, so they are equal
array === anotherArray; // true
array === []; // false
array.push('something');
anotherArray.length; // 1

Because [] is an object, and a comparison of objects only returns true when both sides of the comparison point to the exact same object. You have created two separate objects, so they aren't equal.
var x = []
var y = x
var z = []
x == x // true
x == y // true
x == z // false

Related

Boolean Logic Regarding empty arrays. [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 6 years ago.
quick question:
why does this return false? Just curious.
var myArray = [];
var myArray1 = new Array();
console.log(myArray === myArray1)
Two distinct objects are never === to one another (nor are they ==, for that matter). Object equality means that the two objects are really just one object; that is, that both sides of the === operator are references to the exact same object.
So, this will give you true:
var a = [], b = a;
console.log(a === b);
Every time you do
new Array()
or
= []
A new instance of the Array constructor is assigned to the variable. So when you do a equality check they aint same. Just as same as when two instance of a class aint same.

Why mapping an array using the same function return in different objects? [duplicate]

This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 6 years ago.
I want to know why v.map(...) is not equal to v.map(...) using the same function to do the map
var v = [1,2,3,4,5]
v.map(function(a) {return a+1}) === v.map(function(a) { return a+1;})
Running this on node repl, I've got the result of the second expression as false
When comparing the equality of non-primitives, Javascript checks equality by equality of reference - that is, do both objects being tested refer to the same object in memory?
In this case, they do not - .map returns a new object, and running .map on the same array two different times will return two different references - regardless of the computations done while mapping.
To sum it all up:
v === v is true because v refers to the same object in memory
[1,2,3,4,5] === [1,2,3,4,5] is false because both arrays are different objects in memory (i.e. reference is compared, not values)
.map will always return a new instance of an array - so the result cannot be equal to another .map statement
This is because arrays are compared by reference, not by value, in Javascript.
In other words, doing something like
[1,2] === [1,2];
returns false in Javascript because the two arrays occupy different locations in memory. They are not compared by the actual contents they may have (which is what we would call comparison by value).
In contrast, doing
var x = [1,2];
x === x;
returns true. In this case, the variable x refers (resolves to the memory location of the array) to the same array and this common reference to a memory location is sufficient to yield true.
map() returns an array. Comparing two arrays by value is a fairly complicated affair in Javascript.

how to simplify this statement using indexOf? [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 7 years ago.
How can I simplfy the following text inside the if statement in Javascript using "indexof"?
if (a === 1 || a === 2 || a === 3) {
return "correct";
};
I am guessing an array needs to be made for 1,2, and 3, but am unsure of how to us instanceof after that
*edited to say indexOf instead of instanceOf
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
In your case, instanceof wont help you. You can use indexOf() with array as follow.
var arr = [1, 2, 3];
// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}

Comparing identical arrays in Javascript [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 7 years ago.
I have two identical array and I want to see if it equals and return true
var a = [1,2];
var b = [1,2];
if (a===b) {
return true
}
these two array are obviously identical but I am getting not equal. Can some explain why and if there is an easy way to compare the two?
Problem is you are creating two different arrays, and === check whether both a and b have same reference. Hence your condition fails. There is no built-in code to compare array, however there are libraries for the same. But you simply write a function to compare the arrays by looping.
1. Don't ever use == operator
It doesn't do what you think and it's quite close to be totally useless (for example "1" == [[1]]). Prefer === instead. If the type is the same for both sides == and === do the same, but if they're not == does crazy conversions you will regret.
2. === for arrays checks identity
I.e. it will return true only if the two sides are the very same object, not an object with the same content (whatever 'same' is meant to be).
If you want to check the content you should first decide how to compare elements... for example
my_eqtest([1, [2, 3]], [1, [2, 3]])
should return true or false?
x = [1, 2]
y = [1, 2]
y.myextramember = "foo"
my_eqtest(x, y) // should be true or false?
You should describe (document) what you mean for equality if it's not object identity, otherwise who reads the code will not understand why something is not working (including yourself in a few weeks).
Easiest way would be use a utility library like lodash _.difference
try this:
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}

Why does the typeof a numerical array index in a "for..in" loop considered a string? [duplicate]

This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I noticed that in Javascript a variable used as the index in a for..in loop will be always a string even if I define it the following way:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
for(i in s_array){
alert(typeof(i)); // String
}
Why is it considered a string and not a number?
The for(x in y) syntax is intended to iterate over the properties of an object (not the indexes of an array), and property names are always stored as strings.
The fact that it also works for arrays is a side effect of array elements being properties on the array object.
To understand the difference, consider this code:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
s_array['foo'] = 'bar';
console.log("Object:");
for(i in s_array) {
console.log(i);
}
console.log("Array:");
for(var i = 0, l = s_array.length; i < l; i++) {
console.log(i);
}
which provides the following output:
Object:
0
1
foo
Array:
0
1
There's a foo property on the object, but it's not actually an element inside the array.
Arrays are essentially objects with managed set of indexed keys.
Since every key in an object is of type string hence it is a string as well.
Consider your array as :
{"0" : "foo" , "1" : "bar"}
So your
for(i in s_array){ alert(typeof(i)); }
can be read as
for each key in the s_array
In js arrays are high-level, list-like objects (associative arrays).
indexes eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion.
source: MDN

Categories

Resources