Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. JavaScript Objects > The String, Number, and Boolean Primitive Values Act Li...

The String, Number, and Boolean Primitive Values Act Like Objects When Used Like Objects

When a primitive value is used as if it were an object created by a constructor, JavaScript converts it to an object in order to respond to the expression at hand, but then discards the object qualities and changes it back to a primitive value. In the code below, I take primitive values and showcase what happens when the values are treated like objects.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

// Produce primitive values
var myNull = null;
var myUndefined = undefined;
var primitiveString1 = "foo";
var primitiveString2 = String('foo'); // did not use new, so we get primitive
var primitiveNumber1 = 10;
var primitiveNumber2 = Number('10'); // did not use new, so we get primitive
var primitiveBoolean1 = true;
var primitiveBoolean2 = Boolean('true'); // did not use new, so we get primitive

/* Access the toString() property method (inherited by objects from 
object.prototype) to demonstrate that the primitive values are converted to 
objects when treated like objects. */

// logs "string string"
console.log(primitiveString1.toString(), primitiveString2.toString());

// logs "number number"
console.log(primitiveNumber1.toString(), primitiveNumber2.toString());

// logs "boolean boolean"
console.log(primitiveBoolean1.toString(), primitiveBoolean2.toString());

/* This will throw an error and not show up in firebug lite, as null and 
undefined do not convert to objects and do not have constructors. */
console.log(myNull.toString());
console.log(myUndefined.toString());

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint