I have this code:
var object1 = {same:'test'}
var object2 = {same:'test'};
console.log(object1 === object2)
It returns false in the console.
I also have this code:
var object1 = {same:'test'}
var object2 = object1;
console.log(object1 === object2)
It returns true in the console.
I know '===' is an equality operator, but I don't know how it works on objects.
Why does the first example return false?
See this ball? Its colour is red. Call it ball1.
See this ball? Its colour is red. Call it ball2.
Is ball1 the same object as ball2? No, they are distinct objects that happen to have identical properties.
See this ball? Its colour is red. Call it ball1.
Let's call ball1, ball2.
Is ball1 the same object as ball2? Yes. They are the same ball.
Objects are compared by reference equality, and since object1 and object2 are two distinct instances, they are different objects (think of it as: they occupy different places in memory).
If however you assign object1 to object2, they both point to the same place in memory and thus are equal (they are two references to the same single object, it only exists once in memory). Changing a property through object1.same = 'uiae'; will update the property object2.same as well (because they are in fact the same identical object and the same property)
var object1 ={same:'test'}
var object2 ={same:'test'};
console.log(object1 === object2)
In this case you are creating two different objects. that's why it returns false value in console when checking with === operator.
var object1 ={same:'test'}
var object2 =object1;
console.log(object1 === object2)
In this case you are creating one object and object1 & object2 referencing to created object, that's why it returns true when you are checking with === operator.
In second case if we change the object2["same"]="test2" then object1["same"] value also be changes to test2.
In first case it won't happens like that, because object1 & object2 are two different objects.
refer this:
Object Equality in JavaScript
hopes this is may be helpful.
In the first case Object1 and Object2 are two different reference points(or variables) pointing at two different objects in memory.so when you check them for equality the result is false.
In the second case you are just copying the reference point(address) from Object1 to Object2 meaning both the reference points are now referring the same object in memory.so the result true.
Objects are always compared by reference.
When you assign objects or arrays from one variable to another, it copies a reference to the original object, so the two objects are equal.
Each time you write an object or array literal, it makes a different object or array, so they're not equal, even if the contents are similar.
When you have created object this way, you have created a map.
There is nothing like value of a map as its not of primitive types.
So equals would just check for the reference equality. Hence this fails.
In the second case, the reference equality goes through.
Two different object can't be equal to each other by definition in JavaScript. Equal attributes and values are not important. They have different pointers (first example).
In the second example, you are cloning the object with the reference. So "===" will return true.
In your first example you created two distinct objects with arbitrary content, which is randomly the same: {same:'test'} and {same:'test'}
In your second example you created only one object, and stored it in two variables: object1 and object2
The === checks for object identity, that means the objects in the compared variables must be the same.
Your example does not relate to the == vs === operator difference. As people explained before, your example simply creates two different object and in the next example reference the same. Both == and === would act the same there.
Since objects litterals are always objects litterals and not in any way implicitly convertible, == and === will always act the same for objects litterals. Some other types like NaN, null and the like, you get weird/funny results when comparing with == and ===
This is how javascript handling and comparing objects:
Related
Can somebody please explain the following passage from YDKJS Up & Going to me like I am five:
You should take special note of the == and === comparison rules if
you're comparing two non-primitive values, like objects (including
function and array). Because those values are actually held by
reference, both == and === comparisons will simply check whether the
references match, not anything about the underlying values. For
example, arrays are by default coerced to strings by simply joining
all the values with commas (,) in between. You might think that two
arrays with the same contents would be == equal, but they're not:
var a = [1,2,3];
var b = [1,2,3];
var c = "1,2,3";
a == c; // true
b == c; // true
a == b; // false
What is meant by "references"? Does this mean where the array is held in memory?
well yeah,
you see when you create array named 'arr' for example.
your memory look like this:
so reference comparison actually check if the array reference point the same array in the heap.
stack is for value types and references.
Seems like the following code should return a true, but it returns false.
var a = {};
var b = {};
console.log(a==b); //returns false
console.log(a===b); //returns false
How does this make sense?
The only difference between regular (==) and strict (===) equality is that the strict equality operator disables type conversion. Since you're already comparing two variables of the same type, the kind of equality operator you use doesn't matter.
Regardless of whether you use regular or strict equality, object comparisons only evaluate to true if you compare the same exact object.
That is, given var a = {}, b = a, c = {};, a == a, a == b, but a != c.
Two different objects (even if they both have zero or the same exact properties) will never compare equally. If you need to compare the equality of two object's properties, this question has very helpful answers.
How does this make sense?
Because "equality" of object references, in terms of the == and === operators, is purely based on whether the references refer to the same object. This is clearly laid out in the abstract equality comparison algorithm (used by ==) and the strict equality comparison algorithm (used by ===).
In your code, when you say a==b or a===b, you're not comparing the objects, you're comparing the references in a and b to see if they refer to the same object. This is just how JavaScript is defined, and in line with how equality operators in many (but not all) other languages are defined (Java, C# [unless the operator is overridden, as it is for string], and C++ for instance).
JavaScript has no inbuilt concept of equivalence, a comparison between objects that indicates whether they're equivalent (e.g., have the same properties with the same values, like Java's Object#equals). You can define one within your own codebase, but there's nothing intrinsic that defines it.
As from The Definitive Guide to Javascript.
Objects are not compared by value: two objects are not equal even if they have the same properties and values. This is true of arrays too: even if they have the same values in the same order.
var o = {x:1}, p = {x:1}; // Two objects with the same properties
o === p // => false: distinct objects are never equal
var a = [], b = []; // Two distinct, empty arrays
a === b // => false: distinct arrays are never equal
Objects are sometimes called reference types to distinguish them from JavaScript’s primitive types. Using this terminology, object values are references, and we say that objects are compared by reference: two object values are the same if and only if they refer to the same underlying object.
var a = {}; // The variable a refers to an empty object.
var b = a; // Now b refers to the same object.
b.property = 1; // Mutate the object referred to by variable b.
a.property // => 1: the change is also visible through variable a.
a === b // => true: a and b refer to the same object, so they are equal.
If we want to compare two distinct objects we must compare their properties.
use JSON.stringify(objname);
var a = {name : "name1"};
var b = {name : "name1"};
var c = JSON.stringify(a);
var d = JSON.stringify(b);
c==d;
//true
Here is a quick explanation of why {} === {} returns false in JavaScript:
From MDN Web Docs - Working with objects: Comparing objects.
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.
// Two variables, two distinct objects with the same properties
var fruit = {name: 'apple'};
var fruitbear = {name: 'apple'};
fruit == fruitbear; // return false
fruit === fruitbear; // return false
// Two variables, a single object
var fruit = {name: 'apple'};
var fruitbear = fruit; // Assign fruit object reference to fruitbear
// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true
fruit.name = 'grape';
console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }
For more information about comparison operators, see Comparison operators.
How does this make sense?
Imagine these two objects:
var a = { someVar: 5 }
var b = { another: 'hi' }
Now if you did a === b, you would intuitively think it should be false (which is correct). But do you think it is false because the objects contain different keys, or because they are different objects? Next imagine removing the keys from each object:
delete a.someVar
delete b.another
Both are now empty objects, but the equality check will still be exactly the same, because you are still comparing whether or not a and b are the same object (not whether they contain the same keys and values).
===, the strictly equal operator for objects checks for identity.
Two objects are strictly equal if they refer to the same Object.
Those are two different objects, so they differ.
Think of two empty pages of paper. Their attributes are the same, yet they are not the same thing. If you write something on one of them, the other wouldn't change.
This is a workaround: Object.toJSON(obj1) == Object.toJSON(obj2)
By converting to string, comprasion will basically be in strings
In Javascript each object is unique hence {} == {} or {} === {} returns false. In other words Javascript compares objects by identity, not by value.
Double equal to ( == ) Ex: '1' == 1 returns true because type is excluded
Triple equal to ( === ) Ex: '1' === 1 returns false compares strictly, checks for type even
I have an array of objects in javascript, something like
var arrayobj = [{a:'a'},{b:'b'},{c:'c'}] (but with more complex values).
Now I check the index of some object manually, like arrayobj[1]
And I got Object {b: "b"}
Now I type arrayobj.indexOf({b:'b'});
and the response is -1 (aka not found).
Anyone could tell me why this happens? I have read the documentation on indexOf method and arrays, but I still have no clue.
Thanks in advance!
indexOf checks for equality (specifically strict equality, ===, but it doesn't matter for this question). Two different objects are not equal to each other even if they have the same properties. The object in your array and the one you pass to indexOf are different objects, and so they don't match.
If you searched for the same object, it would find it:
var b = {b:'b'};
var arrayobj = [{a:'a'},b,{c:'c'}];
console.log(arrayobj.indexOf(b)); // 1
The indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present.
arrayobj is an array of objects, In first case arrayobj[1] it will return the element at index 1.
In second case arrayobj.indexOf({b:'b'}) is not referring to the object which in the arrayobj but it is a different object.
arrayobj.indexOf({b:'b'})
You are supplying a new object in the indexOf method although contents are same. IndexOf will check for strict equality so references of the objects need to be the same
When you call arrayobj.indexOf({b:'b'}) the Object {b:'b'} is different from the object in your array. These 2 objects have the same "value" but are distinct in the memory.
For exemple if you do this :
var object = {b:'b'}
var arrayobj = [{a:'a'},object,{c:'c'}]
or
var arrayobj = [{a:'a'},{b:'b'},{c:'c'}]
var object = arrayobj[1]
arrayobj.indexOf(object) will return 1 because it's really the same object and not a "copy"
Javascript IndexOf function will work only for value types and not for reference types in your case. Like when you are passing {b:'b'} to indexOf function then it is all in all a complete different object / reference. If you first fetch object from list and then check that reference in list then it will definitely return greater then -1 if object / reference exist
var arrayobj = [{a:'a'},{b:'b'},{c:'c'}];
var obj = arrayobj[1];
console.log(arrayobj.indexOf(obj)); console.log(arrayobj.indexOf({b:'b'}));
you can use for loop instead of built-in function.
This question already has answers here:
Why are two identical objects not equal to each other?
(9 answers)
Closed 5 months ago.
I know there are similar questions to this on SO, but none of them provide the answer I am looking for.
In JavaScript, if you do the following, the result will be false:
I know it is to do with how JavaScript is defined in the spec, but why is it like that? It is counter-intuitive.
If ("string" === "string") results in being true, then why doesn't ({ } === { }) result in being true?
I saw somewhere that the equality algorithm was designed to be similar to that of C++ or C#, but that's like inventing a brand new engine that uses 1/10th of the fuel and not using it purely for consistency with other cars.
Why was JavaScript defined in this way? Is there a reason behind this decision? Or was it just so it was seen doing the done thing?
{} is a literal to create object in javascript. That is you can replace
var obj = new Object();
with
var obj = {};
So any time you use {} you are creating a new object.
The line you mentioned, {} == {} creates two different objects and both has no properties. Identically they are same, like if you have equals(obj1, obj2) method which compares properties of both obj1 and obj2 and it should return true if both has same value for all properties.
But == operator will not check for properties. It checks if both the objects are pointing to same object/reference.
Whereas
var obj1 = {};
obj2 = obj1;
console.log(obj2 == obj1); //returns true
returns true because obj1 and obj2 are pointing to same reference.
Finally, regarding string "abc" == "abc", here == operator looks for actual string contents and returns true/false based on it.
Strings are immutable, so two strings that have the same contents are functionally indistinguishable.
But objects and arrays can be modified, so just because they happen to have the same contents at some particular time doesn't mean they're the same. You can modify them and they'll then be different.
Another way to put this is that if obj1 == obj2 is true, then when you do obj1.x = 1, it will also change obj2.x.
because a string in javascript even if being an object is considered a primitive, just like a integer or a boolean, and those are always compared by value, because that is what a primitive is, a simple atomic value.. so "string" == "string", 1 = 1 and true == true,
but objects are complex types, they are an aggregate of primitives, and the rules to compare that aggregate, cannot be simplified to standard, is {name:'a',address:'b',phone:'c'} != {name:'a',address:'b'} because does not have the same number of attributes? then in that case will {name:'x',address:'y'} == {name:'a',address'b'}? they have the same attributes, but with different values, or to make it more complex {name:'x',address'y'} == {address:'y',name:'c'}.. does the order matter..
so if the comparison of complex objects can't be done in a simple standard way, it is better to leave to the programmer to implement the rule that applies to the situation..
so what comparison can the language implement that is at least helpful and reliable.. comparing if two object references are equal this will allow to make validations like obj == null or obj == this or if obja == objb so we can at least know of what object/reference are we talking about..
so in summary primitive will always be compared by their value, and complex types are compared by their reference, this is how most languages do, and is not by an inspirations of c++ or whatever is just 'the rules of the game'
I understand the construction function is a special function returning a object. But
> Animal = function (){this.species='animal'}
> a=new Animal()
> b={species:'animal'}
> a==b
==> false
Why?
Comparisons like that are not "deep" comparisons. Either "a" and "b" refer to the exact same object or they don't.
To put it another way, by comparing the two variables you're comparing references to objects, not the objects themselves.
edit — there's a difference between primitive types (booleans, numbers, strings) and object references. Like I said, what you've got in your question is a pair of object references. Two object references are considered equal if they refer to the same object. In your case, they don't. They're two different objects that happen to have the same property with the same value. The properties of the objects do not play a part in the == comparison because that's simply how the language is defined to work.