adding properties to primitive data types other than Array

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

Answers:

Answer

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.

Answer

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!'

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.