why comparing empty object directly showing false? [duplicate] - javascript

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 7 years ago.
I was checking in my console. When i checked empty object directly like {} == {} , it show false.
Why it's showing false ? shouldn't it show true as both are equal ?

When i checked empty object directly like {} == {} , it show false.
You have two different objects here and not one. Here == checks whether the given two objects are same or not.
Scenario 1:
var foo = {}; //new object
var bar = foo; //shared same object
foo == bar;// true
Scenario 2:
var foo = {}; //new object
var bar = {}; //new object
foo == bar;// false
If you still wish to compare two different objects, try this:
var foo = {}; //new object
var bar = {}; //new object
JSON.stringify(foo) == JSON.stringify(bar);// true
Here, JSON.stringify({}) gives string value "{}"

Both are NOT equal. Although they are empty, both refers to different objects.

Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory, which they do not, so the comparison is false.

Related

Why does {} == {} equals false? [duplicate]

This question already has answers here:
Why are two identical objects not equal to each other?
(9 answers)
Closed 4 years ago.
Short question about JavaScript. I tried to execute {} == {} in JavaScript and expected to get true, but it didn't and I want to understand why. Shouldn't {} == {} return true and {} === {} return false?
Because == and === check if the two compared variables are references to the same object, not whether they are identical in value.
Thus a two variables internally referencing each other or a third variable are both == and ===, two new instances of an object are not.
To check if two objects are identical, you could JSON.stringify() them and check whether or not the results are the same.
Most common libraries for JavaScript contain a function to compare two objects, in vanilla JS you can make such a function for yourself:
Object.compare = function(obj1, obj2) {
if (obj1 && obj2) return JSON.stringify(obj1) === JSON.stringify(obj2)
}
console.log(
Object.compare({foo:"bar"}, {foo:"bar"})
);
When comparing two objects with ===, the references will be checked.
These are not two references to the same obejcts, these are two different instances of an empty object.
When comparing with ==, there might be usually some coercion to some common type prior to comparison, following specific rules that are too complicated to be listed here.
But long story short, since you are compariong two objects, there won't be a different check.

Javascript: String vs. Object [duplicate]

This question already has answers here:
Why does ("foo" === new String("foo")) evaluate to false in JavaScript?
(5 answers)
Closed 6 years ago.
I've looked all the questions and answers on stackoverflow, but couldn't find the simple answer to this.
What is exactly the difference between string and object?
For example, if I have this code:
var a = 'Tim';
var b = new String('Tim');
What exactly is the difference?
I understand that new complicates the code, and new String slows it down.
Also, I understand a==b is true, but going more strictly a===b is false. Why?
I seem to fail to understand the process behind the object and string creation.
For example:
var a = new String ('Tim');
var b = new String ('Tim');
a==b is false
a is of type string, whereas b is of type object.
=== includes typechecking and cause string is not an object
a === b will give you a false
new String ('Tim') === new String ('Tim') will evaluate to false too, because both are different objects
For normal strings there is no need to create an object, just create your variable and assign it a value.
And as far as your question regarding why == is true and === is false it's because:
== Compares values
=== Compares values AND type (One is a string, one is an object).
Another example of this is:
var a = 1;
var b = '1';
a == b //True as they both have the same value
a === b //false as one is a string and one is an integer
You can do the following to see the difference:
var a = "foo";
var b = new String("foo");
console.log(a);
console.log(b);
The first one is a string literal and the second is a String object. That's why when you compare them they are not equal but when you compare their values they are. You can read more about literals here.

Why does {} == {} return false? [duplicate]

This question already has answers here:
Why are two identical objects not equal to each other?
(9 answers)
Closed 3 years ago.
I was writing a script, and I had something like
var myObject = {};
if (myObject == {}){
...
}
I was surprised to find that this evaluated to false.
My own findings
Reading up on some of the funny querks javascript does, I found this article, which tells that {} will result in a "truthy" object in an if statement, for example
if ({}){ // true
...
}
Hm, well further ready discuesses String Equality, which for object comparison, says it will return true if they reference the same object. (Even {} === {} returns false)
The only reason I can think that is would return false is that the objects are technically at different memory address, and thus considered different objects.
Because every {} creates a unique object. You can't compare them that way.

Javascript : Check if object has properties [duplicate]

This question already has answers here:
if (key in object) or if(object.hasOwnProperty(key)
(9 answers)
Closed 8 years ago.
There are several answers here how to check if a property exists in an object.
I was always using
if(myObj.hasOwnProperty('propName'))
but I wonder if there is any difference from
if('propName' in myObj){
They are almost equal, the difference is that hasOwnProperty does not check down the prototype chain, while in does.
An example
var test = function() {}
test.prototype.newProp = function() {}
var instance = new test();
instance.hasOwnProperty('newProp'); // false
'newProp' in instance // true
FIDDLE
As noted, Object.hasOwnProperty only returns "own properties", i.e. properties that are added directly, and not properties added to the prototype.
Yes, there is difference. hasOwnProperty() ignores properties and methods which are added with prototype. I try to explain with examples. For instance if you have prototype of object
Object.prototype.something = function() {};
And let's say you have following object
var obj = {
"a" : "one",
"b" : "two"
};
And loop:
for ( var i in obj ) {
//if (obj.hasOwnProperty(i)) {
console.log(obj[i]);
//}
}
Without hasOwnProperty it will output one two function(), while with hasOwnProperty() method only one two
See the differences between First and Second DEMOS

Weird behavior of comparison operator JavaScript when using empty array [duplicate]

This question already has answers here:
Triple equal signs return false for arrays in javascript. why?
(4 answers)
Closed 6 years ago.
Can you explain this weird JavaScript behavior?
First :
[] === [] false
[] == [] false
Why false? The object are identical, thus it should return true.
Second :
[] !== [] true
[] != [] true
Again, why true? the objects are identical.
They're not identical. Object identity is defined by both operands pointing to the same instance.
var a = [],
b = [];
a == b; // false
a == a; // true
Two literals always evaluate to two different instances, which are not considered equal. If you are looking for structural equivalence, see How to compare arrays in JavaScript?.
Objects are not identical. In this case you compare the references to the objects. Easily speaking you compare the addresses in memory where these objects are located. This rule doesn't relate to primitives where you compare the actual values.

Categories