Given
var o = {};
var p = new Object();
p === o; //false
o.__proto__===p.__proto__ // true
why is this false?
please tell me the immediate reason to return false??
The === for objects is defined as:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or
false. Such a comparison is performed as follows:
...
7. Return true if x and y refer to the same object. Otherwise, return
false.
In this case, although both are empty objects, they are created separately and hence do not refer to the same object.
As a side note, both constructions do the same thing; but it is common practice to use {}.
The two objects contain the same thing (i.e. nothing) but they are not the same object.
Javascript's object equality test requires that the two parameters refer to the exact same object.
JavaScript strict comparison for objects tests whether two expressions refer to the same objects (and so does the normal equals operator).
You create the first object using object literal {} which creates a new object with no properties.
You create the second object by calling Object constructor as a function. According to section 15.2.1.1 of ECMAScript Language Specification this also creates a new object just as if new Object() was used.
Thus you create two objects, store their references under p and o and check whether p and o refer to the same object. They don't.
Every time you create an object, the result has its own, distinct identity. So even though they are both "empty", they are not the same thing. Hence the === comparison yields false.
Using the === , the result will show if items on both side is the "Same Instance"
If you like to comparing two item are same type, you should use:
var o1 = {};
var o2 = new Object();
alert( typeof(o1) === typeof(o2));
and if you like to tell if the two object is considered equal (in properties and values), you should try underscore.js library and use the isEqual function.
Is this homework?
In that case, I will only give you some hints:
- Think about what the first two lines do. Do o and p refer to the same object after those two lines?
- Look up exactly what === does. Does it compare two objects to see if their structure are the same? Or does it compare the objects based on their identity?
Object is an unordered collection of properties each of which contains a primitive value, object, or function. So, each object has properties and prototypes and there's no any sense to compare the one.
Related
I read this a lot in many JavaScript introductions. I just don't understand it. I always think of objects as something with methods and properties.
Arrays I understand, since it has key value pair.
How about "Strings" or "Numbers" or "functions" ?
These things above listed seem to be like functions to me. This means you input something, you get something out. You don't really get the access properties or anything. There's no dot notation used in arrays or this list of "objects".
Does anyone code some examples of each of these with dot notations which its methods and properties are being accessed? I suspect that definition of object is probably limited since I did start learning about JavaScript...
No, not everything is an object in JavaScript. Many things that you interact with regularly (strings, numbers, booleans) are primitives, not objects. Unlike objects, primitive values are immutable. The situation is complicated by the fact that these primitives do have object wrappers (String, Number and Boolean); these objects have methods and properties while the primitives do not, but the primitives appear to have methods because JavaScript silently creates a wrapper object when code attempts to access any property of a primitive.
For example, consider the following code:
var s = "foo";
var sub = s.substring(1, 2); // sub is now the string "o"
Behind the scenes, s.substring(1, 2) behaves as if it is performing the following (approximate) steps:
Create a wrapper String object from s, equivalent to using new String(s)
Call the substring() method with the appropriate parameters on the String object returned by step 1
Dispose of the String object
Return the string (primitive) from step 2.
A consequence of this is that while it looks as though you can assign properties to primitives, it is pointless because you cannot retrieve them:
var s = "foo";
s.bar = "cheese";
alert(s.bar); // undefined
This happens because the property is effectively defined on a String object that is immediately discarded.
Numbers and Booleans also behave this way. Functions, however, are fully-fledged objects, and inherit from Object (actually Object.prototype, but that's another topic). Functions therefore can do anything objects can, including having properties:
function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea
That’s right: in JavaScript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key–value pairs. A key is always a string or a symbol, and a value can be anything including strings, integers, booleans, functions, other objects etc. So I can create a new object like this:
var obj = {}; // This is not the only way to create an object in JS
and add new key–value pairs into it:
obj['message'] = 'Hello'; // You can always attach new properties to an object externally
or
obj.message = 'Hello';
Similarly, if I want to add a new function to this object:
obj['showMessage'] = function(){
alert(this['message']);
}
or
obj.showMessage = function() {
alert(this.message);
}
Now, whenever I call this function, it will show a pop-up with a message:
obj.showMessage();
Arrays are simply those objects which are capable of containing lists of values:
var arr = [32, 33, 34, 35]; // One way of creating arrays in JS
Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them. So you can access an item using its index:
alert(arr[1]); // This would show 33
An array object, just like any other object in JS, has its properties, such as:
alert(arr.length); // This would show 4
For in-depth detail, I would highly recommend John Resig’s Pro JavaScript Techniques.
The sentence "In JavaScript, ALMOST everything is an object" is correct, because the MAIN code-units (objects, functions, arrays) are JavaScript-objects.
JavaScript code uses 9 different-units plus 1 (multiple):
- 01. array
- 02. boolean
- 03. function
- 04. null
- 05. number
- 06. object
- 07. regexp
- 08. string
- 09. undefined
- 10. multiple
BUT JavaScript-objects:
- are NOT same creatures as the 'objects' in other object-oriented-languages.
- they are a collection of name-value-pairs.
- all have a function of creation (its constructor).
- all INHERIT the members of the prototype-object of its constructor and this is its prototype.
- all functions are objects BUT NOT all objects are functions.
- functions have scope, objects NOT (a design flaw in my opinion).
- Object, Function, Array, String, ... with first CAPITAL are functions!!!
- it is more important the differences of JS objects and functions, than its commonnesses.
- the name 'instance' in JS has different meaning with the name 'instance' in knowledge-theory where an instance inherits the attributes of its generic-concept. In JS denotes only its constructor. JavaScript got the name 'instance' from 'class-based-inheritance' ool (java) where it is an appropriate name because those objects inherit the attributes of classes.
A better name for the JS-keyword 'instanceof' is 'objectof'.
JS-functions ARE JS-objects because:
1) they can have members like JS-objects:
> function f(){}
undefined
> f.s = "a string"
"a string"
> f.s
"a string"
2) they have a constructor-function, like all JS-objects, the Function function:
> (function f(){}) instanceof Function
true
3) as all JS-objects, their prototype-object is the same with its constructor prototype:
> (function f(){}).__proto__ === Function.prototype
true
> ({}).__proto__ === Object.prototype
true
> (new Object).__proto__ === Object.prototype
true
4) of course, JS-functions as SPECIFIC JS-objects have and extra attributes, like all functions in programming-languages, that JS-objects do not have like you can call (execute) them with input and output information.
EVERYTHING is NOT an object, because, for example, we can NOT add members to a literal string:
> var s = "string"
undefined
> s.s2 = "s2string"
"s2string"
> s.s2
undefined
Based on developer.mozilla.org and also ECMAScript specification the answer is no. Technically not everything is object.
https://developer.mozilla.org/en-US/docs/Glossary/Primitive
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 7 primitive data types: string, number, bigint, boolean, null, undefined, symbol
A primitive is not an object and has no methods and It is also immutable. Except for null and undefined, all the other primitive have a wrap object around them to provide you some functions that you can use. For example String for the string primitive.
https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
So here in the following code when you call toUpperCase() on a primitive data name JavaScript will automatically wrap the string primitive and call toUpperCase function of String object
var name = 'Tom';
console.log(name);
name.toUpperCase();
console.log(name);
In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.
Also note that JavaScript distinguishes between String objects and primitive string values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects
var nameP = 'Tom';
var nameO = new String(nameP);
typeof nameP // "string"
typeof nameO // "object"
Not everything is an object in javaScript. JavaScript has primitives and objects.
There are six primitives-null,undefined,string,number,boolean and symbol.
It might seem like everything is acting as an object because of the properties and function that can be accessed.for example-
var stringvar="this string";
typeof stringvar; // "string"
stringvar.length; //11
now since "stringvar" is a string type ,which is a primitive type,it should not be able to accesss property length.It can do so because of something called Boxing.Boxing is the process where any primitive type is converted to an Object type and the reverse is called Unboxing.These object types or Object wrappers are created with the view that there are some common operations that one might need to perform with the primitive values.They contain useful methods and properties and are prototype linked to the primitives.
As far as the Objects are concerned,key value pairs can be added to every object,even to the arrays.
var arr=[1,2,3];
arr.name="my array";
arr; //[1,2,3,name:'my array']
this does not mean that the fourth element of the array is "name:'my array'"."name" is a property that can be called with dot notation(arr.name) or brackets notation(arr["name"]).
I would say "Everything in Javascript is not an object (because of primitives) but everything in javascript leads back to an object (because of wrappers and Object constructor)"
I read this a lot in many JavaScript introductions. I just don't understand it. I always think of objects as something with methods and properties.
Arrays I understand, since it has key value pair.
How about "Strings" or "Numbers" or "functions" ?
These things above listed seem to be like functions to me. This means you input something, you get something out. You don't really get the access properties or anything. There's no dot notation used in arrays or this list of "objects".
Does anyone code some examples of each of these with dot notations which its methods and properties are being accessed? I suspect that definition of object is probably limited since I did start learning about JavaScript...
No, not everything is an object in JavaScript. Many things that you interact with regularly (strings, numbers, booleans) are primitives, not objects. Unlike objects, primitive values are immutable. The situation is complicated by the fact that these primitives do have object wrappers (String, Number and Boolean); these objects have methods and properties while the primitives do not, but the primitives appear to have methods because JavaScript silently creates a wrapper object when code attempts to access any property of a primitive.
For example, consider the following code:
var s = "foo";
var sub = s.substring(1, 2); // sub is now the string "o"
Behind the scenes, s.substring(1, 2) behaves as if it is performing the following (approximate) steps:
Create a wrapper String object from s, equivalent to using new String(s)
Call the substring() method with the appropriate parameters on the String object returned by step 1
Dispose of the String object
Return the string (primitive) from step 2.
A consequence of this is that while it looks as though you can assign properties to primitives, it is pointless because you cannot retrieve them:
var s = "foo";
s.bar = "cheese";
alert(s.bar); // undefined
This happens because the property is effectively defined on a String object that is immediately discarded.
Numbers and Booleans also behave this way. Functions, however, are fully-fledged objects, and inherit from Object (actually Object.prototype, but that's another topic). Functions therefore can do anything objects can, including having properties:
function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea
That’s right: in JavaScript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key–value pairs. A key is always a string or a symbol, and a value can be anything including strings, integers, booleans, functions, other objects etc. So I can create a new object like this:
var obj = {}; // This is not the only way to create an object in JS
and add new key–value pairs into it:
obj['message'] = 'Hello'; // You can always attach new properties to an object externally
or
obj.message = 'Hello';
Similarly, if I want to add a new function to this object:
obj['showMessage'] = function(){
alert(this['message']);
}
or
obj.showMessage = function() {
alert(this.message);
}
Now, whenever I call this function, it will show a pop-up with a message:
obj.showMessage();
Arrays are simply those objects which are capable of containing lists of values:
var arr = [32, 33, 34, 35]; // One way of creating arrays in JS
Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them. So you can access an item using its index:
alert(arr[1]); // This would show 33
An array object, just like any other object in JS, has its properties, such as:
alert(arr.length); // This would show 4
For in-depth detail, I would highly recommend John Resig’s Pro JavaScript Techniques.
The sentence "In JavaScript, ALMOST everything is an object" is correct, because the MAIN code-units (objects, functions, arrays) are JavaScript-objects.
JavaScript code uses 9 different-units plus 1 (multiple):
- 01. array
- 02. boolean
- 03. function
- 04. null
- 05. number
- 06. object
- 07. regexp
- 08. string
- 09. undefined
- 10. multiple
BUT JavaScript-objects:
- are NOT same creatures as the 'objects' in other object-oriented-languages.
- they are a collection of name-value-pairs.
- all have a function of creation (its constructor).
- all INHERIT the members of the prototype-object of its constructor and this is its prototype.
- all functions are objects BUT NOT all objects are functions.
- functions have scope, objects NOT (a design flaw in my opinion).
- Object, Function, Array, String, ... with first CAPITAL are functions!!!
- it is more important the differences of JS objects and functions, than its commonnesses.
- the name 'instance' in JS has different meaning with the name 'instance' in knowledge-theory where an instance inherits the attributes of its generic-concept. In JS denotes only its constructor. JavaScript got the name 'instance' from 'class-based-inheritance' ool (java) where it is an appropriate name because those objects inherit the attributes of classes.
A better name for the JS-keyword 'instanceof' is 'objectof'.
JS-functions ARE JS-objects because:
1) they can have members like JS-objects:
> function f(){}
undefined
> f.s = "a string"
"a string"
> f.s
"a string"
2) they have a constructor-function, like all JS-objects, the Function function:
> (function f(){}) instanceof Function
true
3) as all JS-objects, their prototype-object is the same with its constructor prototype:
> (function f(){}).__proto__ === Function.prototype
true
> ({}).__proto__ === Object.prototype
true
> (new Object).__proto__ === Object.prototype
true
4) of course, JS-functions as SPECIFIC JS-objects have and extra attributes, like all functions in programming-languages, that JS-objects do not have like you can call (execute) them with input and output information.
EVERYTHING is NOT an object, because, for example, we can NOT add members to a literal string:
> var s = "string"
undefined
> s.s2 = "s2string"
"s2string"
> s.s2
undefined
Based on developer.mozilla.org and also ECMAScript specification the answer is no. Technically not everything is object.
https://developer.mozilla.org/en-US/docs/Glossary/Primitive
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 7 primitive data types: string, number, bigint, boolean, null, undefined, symbol
A primitive is not an object and has no methods and It is also immutable. Except for null and undefined, all the other primitive have a wrap object around them to provide you some functions that you can use. For example String for the string primitive.
https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
So here in the following code when you call toUpperCase() on a primitive data name JavaScript will automatically wrap the string primitive and call toUpperCase function of String object
var name = 'Tom';
console.log(name);
name.toUpperCase();
console.log(name);
In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.
Also note that JavaScript distinguishes between String objects and primitive string values.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects
var nameP = 'Tom';
var nameO = new String(nameP);
typeof nameP // "string"
typeof nameO // "object"
Not everything is an object in javaScript. JavaScript has primitives and objects.
There are six primitives-null,undefined,string,number,boolean and symbol.
It might seem like everything is acting as an object because of the properties and function that can be accessed.for example-
var stringvar="this string";
typeof stringvar; // "string"
stringvar.length; //11
now since "stringvar" is a string type ,which is a primitive type,it should not be able to accesss property length.It can do so because of something called Boxing.Boxing is the process where any primitive type is converted to an Object type and the reverse is called Unboxing.These object types or Object wrappers are created with the view that there are some common operations that one might need to perform with the primitive values.They contain useful methods and properties and are prototype linked to the primitives.
As far as the Objects are concerned,key value pairs can be added to every object,even to the arrays.
var arr=[1,2,3];
arr.name="my array";
arr; //[1,2,3,name:'my array']
this does not mean that the fourth element of the array is "name:'my array'"."name" is a property that can be called with dot notation(arr.name) or brackets notation(arr["name"]).
I would say "Everything in Javascript is not an object (because of primitives) but everything in javascript leads back to an object (because of wrappers and Object constructor)"
I have the following code -
var a = new Object();
var b = {};
console.log(a == b || a === b);
and it prints false. What is the reason behind this?
When you compare objects, you are testing to see if they are the same object.
You have two different (albeit effectively identical) objects.
When you compare the equality of objects you compare whether the two objects have the same instance (meaning that the variables you compare do reference the same memory).
You have two different instances, so equality comparison yields false.
If you want to check if all properties of two objects have equal values it is a different thing and you really have to check equality for each object property.
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 know that identical objects are not equal, i.e:
var obj = { name: "Value" };
var obj2 = { name: "Value" };
console.log("obj equals obj2: " + (obj === obj2)); //evaluates to false
Yet primitive types are:
var str = "string1";
var str2 = "string1";
console.log("str equals str2: " + (str === str2)); //evaluates to true
My question is why. Why are objects and primitives treated differently? If an object is nothing but an empty container, with only the attributes you specify to put in the container, why wouldn't the container's identical attributes evaluate to be the same? I looked around for this answer on SO and elsewhere, but didn't find an answer.
Is a JS object treated as something different in the DOM than a primitive type?
Thanks
This seems to really be a question about === so let's look at the Strict Equality Comparison Algorithm, in which point 7 says
Return true if x and y refer to the same object. Otherwise, return false.
So what does it mean to be "the same object"? It means they don't just look like eachother, but are at the same place in memory too. This means that the only time when an Object is === to an Object is when they're the same thing.
var a = {},
b = {}, // identical to `a`
c = a; // same as `a`
a === b; // false
a === c; // true
b === c; // false
When a variable's value is an object, well, it isn't an object: it's a reference to an object. Two variables that contain references to the same object are indeed equal:
var myObj = { hello: "world" };
var a = myObj;
var b = myObj;
if (a == b) alert("YES!!"); // YES!!
When the == operator has object references on both sides, the comparison made is to test whether the objects refer to the same object. When primitive values are involved, the semantics are different: the values are directly compared.
Generally, === operator checks for types, and if they are the same, checks values. Object type contains a reference, so, to be equal, they have to reference the same object and be of the same type. String literal value is not a reference, it is a value, so the === will produce true for string literals, but not for "abc" === new String("abc") because latter is an Object.
More information can be found here: A lot of details can be explored from here: Which equals operator (== vs ===) should be used in JavaScript comparisons?
First off, JavaScript objects aren't part of the DOM. The DOM (Document Object Model) are the HTML elements which make up your page. They cooperate together, but aren't directly linked.
Basically, yes, primitives are a special case. You can kind of think of it as if the value of a primitive is a constant (in a sense).
For example, take the example of the number 5. No matter how many times I declare 5, 5 will always equal 5. Thus, it isn't a stretch to say that {var a holding the value 5} is equivalent to {var b holding the value 5}. This concept is a little fuzzier with strings, but it still holds. A string that is "abc" is always the same as any other variable holding a string that is "abc".
This doesn't apply to objects either.
If you have two variables hold the same object, they are eqivalent.
var a = {};
var b = a;
console.log(a == b); // true
console.log(a === b); // true
However, if we create two objects that look similar:
var a = {};
var b = {};
console.log(a == b); // false
console.log(a === b); // false
This seems a bit weird at first, but think about the inner workings that are going on. Consider that when you pass an object in to a function, if you change that object, it is changed outside of the function to. It's passed by reference.
This means you can think of a pointer (a memory address) being stored in the variables. So, if you imagine that they have memory address in them (like 0x123456 and 0x654321), then it makes a little more sense (0x123456 and 0x654321 are different, so you wouldn't expend them to be equal). They are two separate things taking up their own area in the memory.
Make sense?
You can answer to this question at several levels.
strings
Factually, yes, strings are handled differently from objects as far as strict comparison operator is concerned.
Semantically, that is more convenient than having to resort to strcmp or equivalent mechanisms to compare two strings.
Implementation-wise, the cost is neglectible, so JavaScript can offer you that convenience.
By the way, people telling the strict equality operator checks if both variables point to the same memory location are wrong. In case of strings, === will succeed if the string contents are equal, wherever they might be located in memory.
Objects
Semantically, contrary to primitive types like numbers or strings, it is difficult to offer a consistent set of comparison operators for objects.
You could do an in-depth comparison for equality, but greater/lower operators would make little sense.
The choice of Javascript is rather inconsistent here.
the semantics of equality comparison (be it == or ===) are limited to references
(i.e. == or === will succeed if the references are equal).
Implementation-wise, a deep comparison could be quite costly.
There are also subtelties as how to interpret undefined properties.
At any rate, JavaScript did not choose to implement a deep comparison, so if you want one, you'll have to do it yourself.
And there have been terabytes of code written to try and provide the ideal in-depth object comparison function.
ordered comparison is handled quite differently.
You can define a valueOf method that will return whatever primitive value you want to be used for ordered comparison, e.g
myObject.prototype.valueOf = function(){return this.my_comparison_value; };
If not explicitely defined, valueOf will default to "[object Object]".
So if you don't supply a valueOf method:
< and > operators will always return false (which kind of makes sense).
>= and <= will always return true, regardless of the references being equal or not
(which makes a lot less sense).
Now if you take the pain to define a valueOf, equality comparison will still not use it.
The only way to have a consistent behaviour would be to combine <= and >=, e.g.
if (a >= b && a <= b) { // equality using valueOf
For browser-supplied primitive objects like DOM elements, the behaviour of ordering operators depends on what the browser decided to return as a default value.
I would not recomend using that unless you really know what you're doing.