arozwalak
7/13/2015 - 8:53 AM

Javascript: Primitive Wrappers

Javascript: Primitive Wrappers

// a primitive number
var n = 100;
console.log(typeof n); // "number"

// a Number object
var nobj = new Number(100);
console.log(typeof nobj); // "object"
// a primitive string be used as an object
var s = "hello";
console.log('s.toUpperCase()); // "HELLO"

// the value itself can act as an object
"monkey".slice(3, 6); // "key"

// same for numbers
(22 / 7).toPrecision(3); // "3.14"

Because primitives are not objects, they cannot be augmented with properties

// primitive string
var greet = "Hello there";

// primitive is converted to an object
// in order to use the split() method
greet.split(' ')[0]; // "Hello"

// attemting to augment a primitive is not an error
greet.smile = true;

// but it doesn't actually work
typeof greet.smile; // "undefined"