I mean not equal, but literally one....two things pointing to the same place in memory.
For example, a and b here should theoretically be identical...b is a sort of pointer to a.
var a = function(){alert("hi");}
var b = a;
=== is not the answer....two things can be the same in every way but not literally the same object in memory.
Edit: === IS the answer! Silly me.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
An expression comparing Objects is only true if the operands reference the same Object.
Two identical objects never return true when compared. They really have to be "one".
Related
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:
I am confused about placement of operators:
Given:
var a = [0, 1, 2];
So far as I can tell, each of the following is correct:
var len = a.length;
var lastElt = a.pop();
var str = String(a);
var typeStr = typeof a;
Is there an easy way to remember/think about whether the operator goes before or after the operand and whether it requires parentheses? Or is it simply rote memorization?
Thanks.
Let's go:
case #1
var len = a.length;
In this case you're calling the method lenght of the array store in the variable a.
case #2
var lastElt = a.pop();
As before, here you're calling the method pop of the array.
case #3
var str = String(a);
You aren't not calling any array's method. Here you're casting the array. i.e. you are stringifying the array.
case #4
var typeStr = typeof a;
Here you also aren't calling any array's method. You are calling the typeof method of the window object and passing the array a as an argument.
As you can see. In the first two cases, you are calling array's methods. In the last two cases, you are calling window object's methods and passing your array as an argument.
Your list there mostly consists of things that are not operators:
length is a property belonging to Array objects. It returns the number of items in the Array.
pop() is a method belonging to Array objects. It removes the last item from the Array and retuns it.
String() is a global object which is the constructor for a String object. It takes any object as a parameter and converts it to a String
typeof is an operator. It returns a string that indicates the type of the subsequent operand.
For more reference, here is some information about JavaScript operators.
I highly recommend searching Google for some beginning JavaScript tutorials so you can learn the basic concepts.
Thanks for all the prompt replies. In reply to the question 'What do you mean by "operator" here?' I come from a background of mathematics and (lately) c programming. By "operator" I wanted to speak abstractly about anything that mapped its argument to something useful, using it to include methods, properties, etc., without enumerating them. My attempt to abstract these is probably the source of my confusion. I now understand that what is required is rote memorization, something like declensions in Latin ;-).
Operators refer to +,=*,/ etc.
I don't think there is an easy way to remember. If it is a 'property', there will be no parentheses. If it is a function, there will be parentheses. I always remember that length is a property of an array, and that push and pop are actions you can do to the array. Type casting always starts with the 'type' capitalized followed by what you want casted in the parenthesis. typeof is just a weird one.
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.
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.