If JavaScript will readily coerce between primitives and objects why adding properties to it results to undefined??
var a = "abc";
var b = a.length
console.log(b)//outputs 3
Does coercion allow me to assign values to primitives?If not why ?
Does coercion allow me to assign values to primitives?
Yes. The primitive is wrapped in an object, and a property is created on that. No exception will be thrown.
why adding properties to it results to undefined?
The adding itself does result in the value.
var str = "abc";
console.log(str.someProperty = 5); // 5
Yet, what you're asking for is getting a property from a primitive. This will return in undefined since the primitive is wrapped in a new wrapper object - not the one which you assigned the property on:
console.log(str.someProperty); // undefined
It only works for special properties like .length that are created with the object, or inherited ones like slice or charAt methods (see the docs for those).
If you wanted such a thing, you'd need to create the wrapper object explicitly and store it somewhere:
var strObj = new String("abc");
strObj.someProperty = 5;
console.log(strObj.someProperty); // 5
// coercion and the `toString` method will even make the object act like a string
console.log(strObj + "def"); // "abcdef"
Why don't you do it like this?
var abc=Number(3);
abc.foo="bar";
abc; //3
abc.foo; //bar
#Bergi indeed, sorry for this. I've missed the new statement. Here it is:
var abc=new Number(3);
abc.foo="bar";
abc; //3
abc.foo; //bar
At least it works just right. I don't know what else someone may need :)
primitives... coercion... blah.
Related
I would love a clear explanation as to better understand what's going on here?
I can create what look like primitive types with Object. It looks like a number but not quite for a string. I was under the impression that Object() was used to create all objects in js (ie of type object) but not primitive types, like number, string boolean.
There are times when a primitive type (Boolean, Number or String) needs to be converted to object albeit temporarily.
Look at this example:
var str = 'javascript';
str = str.substring(4);// You get "script" but how?
How can you call a function on something that is not an object? The reason is that primitive value is wrapped into Object(String) on which substring() method is defined. If it was not done, you would not be able to call the method in the primitive type. Such wrappers are called Primitive Wrappers.
Also, it doesn't mean that str has now become an object. So, if you said:
str.myProp = 10;
and then console.log(str.myProp);//You would get undefined
The difference between a reference type and a primitive wrapper object is lifetime. Primitive wrappers die soon.
So you can think of
var str = 'javascript';
str = str.substring(4);// You get "script" but how?
As these lines:
var str = new String(“javascript”);
str = str.substring(4);
str = null;
Now coming to what you are doing:
number = Object(5);
Here you are wrapping a number primitive into an object. It is as if you had written:
number = new Number(5);
Here, Object(5) is behaving as a factory and depending on the type of the input(number, string), it gives back object by wrapping primitive value into it.
So, Object(5) is equivalent to new Number(5) and Object('test') is as if saying new String('test').
Hope this helps!
The notion of primitives and objects is slightly implementation dependent. But you can think of it like this:
Primitives are not objects. They have their own special semantics, such as the string "hello" is the same no matter how many times you create one. However, the object new String("hello") should return a new string every time.
In many implementations, there is auto-boxing and unboxing of primitives when they need to act like objects and vice-versa. I would suggest reading this question for more details: What is the difference between string literals and String objects in JavaScript?
You can use Object.prototype.valueOf() to get [[PrimitiveValue]] 5 or "test".
var number = new Object(5);
var aString = new Object("test");
console.log(number.valueOf(), aString.valueOf());
5.toString();
As you can see Number is an object. But number is not. In some cases primitives are wrapped by objects to implement object like behaviours...
5 // primitive type
Object(5) // wrapper of that primitive type
5.toString() === Object(5).toString() //...
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.
There is a way to add a member-function or member-property to Number, String, ect...-Variables with the help of the prototype-property:
Number.prototype.member = function(){ console.log('number-member-function called'); };
or with help of the proto-property of the variables themselves:
var num = 7;
num.__proto__.member = function(){ console.log('number-member-function called'); };
Just like to any other kind of JavaScript-types.
But what is the difference of the implementation of Primtives and Objects in JavaScript so that the code below does not work for Numbers but for Objects?
var num = 7;
num.member = function(){ console.log('number-member-function called'); };
num.member(); // TypeError: num.member is not a function
var obj = {};
obj.member = function(){ console.log('object-member-function called'); };
obj.member(); // object-member-function called
Does anybody know approximatly how JavaScript Primitves and Objects are implemented under the hood? Because all JavaScript-implementations in all browsers must be done identically or almost for there is an error thrown with the Number-Function called member.
When you use the literal notation for the boolean, string and number types, the constructors (Boolean, String, Number) are not used. The primitive types still behaves almost like they had been instantiated with the new operator, but are truly primitive types.
Only when you are trying to use them as objects or you are trying to use a property of a constructor, the JavaScript interpreter creates a wrapper object around them behind the scenes.
After this, the wrapper objects gets discarded and you are dealing again with the primitive type.
So:
var num = 7; //primitive
// You are trying to use num as an object: a wrapper object gets created and discarded just after the assignment
num.member = function(){ console.log('number-member-function called'); };
// This will throw an error, because here num is primitive again (member was defined on the discarded wrapper)
num.member();
More on this topic can be found on the book "JavaScript Enlightenment" by Cody Lindley, based on the ECMA-262, Edition 3 specification.
I'm not supposed to add elements to an array like this:
var b = [];
b.val_1 = "a";
b.val_2 = "b";
b.val_3 = "c";
I can't use native array methods and why not just an object. I'm just adding properties to the array, not elements. I suppose this makes them parallel to the length property. Though trying to reset length (b.length = "a string") gets Uncaught RangeError: Invalid array length.
In any case, I can still see the properties I've set like this:
console.log(b); //[val_1: "a", val_2: "b", val_3: "c"]
I can access it using the dot syntax:
console.log(b.val_1); //a
If an array is just an object in the same way a string or a number is an object, why can't (not that I'd want to) I attach properties to them with this syntax:
var num = 1;
num.prop_1 = "a string";
console.log(num); //1
I cannot access its properties using dot syntax
console.log(num.prp); //undefined
Why can this be done with array and not with other datatypes. For all cases, I should use {} and would only ever need to use {}, so why have arrays got this ability?
JSBIN
Because arrays are treated as Objects by the language, you can see this by typing the following line of code:
console.log(typeof []) // object
But other types like number literals, string literals NaN ... etc are primitive types and are only wrapped in their object reprsentation in certain contexts defined by the language.
If you want to add properties or methods to a number like that, then you can use the Number constructor like this:
var num = new Number(1);
num.prop_1 = "fdadsf";
console.log(num.prop_1);
Using the Number constructor returns a number object which you can see by typing the following line:
console.log(typeof num); // object
While in the first case:
var num = 1;
console.log(typeof num) // number
EDIT 2: When you invoke a method on a number literal or string literal for instance, then that primitive is wrapped into its object representation automatically by the language for the method call to take place, for example:
var num = 3;
console.log(num.toFixed(3)); // 3.000
Here num is a primitive variable, but when you call the toFixed() metohd on it, it gets wrapped to a Number object so the method call can take place.
EDIT: In the first case, you created a string like this first var str = new String(), but then you changed it to str = "asdf" and then assigned the property str.var_1 = "1234".
Of course, this won't work, because when you assigned str = "asdf", str became a primitive type and the Object instance that was originally created is now gone, and you can't add properties to primitives.
In the second, it didn't output undefined like you said, I tested it in Firebug and everything worked correctly.
EDIT 3:
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
This is taken from MDN Documentation, when you use string like that var p = String(3) it becomes a conversion function and not a constructor and it returns a primitive string as you can see from the quote above.
Regarding your second comment, I didn't understand how my comment has been defied, because if you try to console.log(p.pr) you'll get undefined which proves p is a primitive type and not an object.
If an array is just an object in the same way a string or a number is an object,
An array is different than strings, numbers, booleans, null and undefined. An array IS an object, while the others in the list are primitive values. You can add properties to the array just like you would with any other object, anything different being just what makes arrays special (the length property you mentioned for example). You cannot add properties or call methods on primitive values.
In this previous answer i talked about the use of Object wrappers over primitive values. Feel free to read it to see more about Object wrappers. The following will be a very short example:
console.log('TEST'.toLowerCase()) // 'test'
While it may seem that the toLowerCase method is called on the string 'TEST', in fact the string is converted automatically to a String object and the toLowerCase method is called on the String object.
Each time a property of the string, number or boolean is called, a new Object wrapper of the apropriate type is created to get or set that value (setting properties might be optimized away entirely by the browser, i am not sure about that).
As per your example:
var num = 1; // primitive value
num.prop_1 = "a string"; // num is converted to a Number, the prop_1 property is set on the Object which is discarded immediately afterwards
console.log(num); //1 // primitive value
console.log(num.prp); // num is converted to a Number, which doesn't have the prp property
My example:
Number.prototype.myProp = "works!";
String.prototype.myFunc = function() { return 'Test ' + this.valueOf() };
Boolean.prototype.myTest = "Done";
console.log(true.myTest); // 'Done'
console.log('really works!'.myFunc()); // 'Test really works!'
var x = 3;
console.log(x.myProp.myFunc()); // 'Test works!'
console.log(3['myProp']); // 'works!'
On the other hand:
console.log(3.myProp); // SyntaxError: Unexpected token ILLEGAL
The number isn't necessarily treated differently, that syntax just confuses the parser. The following example should work:
console.log(3.0.myProp); // 'works!'
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.
First I tried this example in the console:
a = b = {};
a.foo = 'bar';
console.log(b.foo);
The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.
a = b = 'foo';
a = 'bar';
console.log(b);
That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.
Why does this happen?
N.B. This example could be simplified even more with the following code:
a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);
a = 'foo';
b = a;
a = 'bar';
console.log(b);
(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.
a = b = {};
a and b are now pointers to the same object. So when you do:
a.foo = 'bar';
It sets b.foo as well since a and b point to the same object.
However!
If you do this instead:
a = 'bar';
you are saying that a points to a different object now. This has no effect on what a pointed to before.
In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.
But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.
Your question has already been satisfyingly answered by Squeegy - it has nothing to do with objects vs. primitives, but with reassignment of variables vs. setting properties in the same referenced object.
There seems to be a lot of confusion about JavaScript types in the answers and comments, so here's a small introduction to JavaScript's type system:
In JavaScript, there are two fundamentally different kinds of values: primitives and objects (and there is no thing like a 'hash').
Strings, numbers and booleans as well as null and undefined are primitives, objects are everything which can have properties. Even arrays and functions are regular objects and therefore can hold arbitrary properties. They just differ in the internal [[Class]] property (functions additionally have a property called [[Call]] and [[Construct]], but hey, that's details).
The reason that primitive values may behave like objects is because of autoboxing, but the primitives themselves can't hold any properties.
Here is an example:
var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);
This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.
Think of it like this:
var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created
You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.
In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.
here is my version of the answer:
obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"
// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"
// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory
You are setting a to point to a new string object, while b keeps pointing to the old string object.
In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.
The difference is between simple types and objects.
Anything that's an object (like an array or a function) is passed by reference.
Anything that's a simple type (like a string or a number) is copied.
I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.