Skip to content

Instantly share code, notes, and snippets.

@sean-roberts
Last active December 18, 2015 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-roberts/5710678 to your computer and use it in GitHub Desktop.
Save sean-roberts/5710678 to your computer and use it in GitHub Desktop.
Wrapper Objects in JS : literal variables of type string, number, and boolean are not objects but they seem to have properties, why is that? Because, when they are accessed, JS converts the value into its object type temporarily. Then once the method or property is resolved, this new object is discarded. This temporary object is the wrapper obje…
//start with a string literal
var a = "Hello, World";
//add a new property to that string
a.dateCreated = "6-4-2013";
//try to access that property
var b = a.dateCreated;
//b is still undefined
//Why?
//because when you access as string (number or boolean as well)
// you're really accessing the wrapper object that is created just like calling new String("Hello, World")
//and discarded it immediately after use
//so, technically, by the time you tried to use dateCreated to assign it to b, the object
// that you attached that property to does not exist.
//Also worth noting,
//you can create wrapper objects by invoking the String(), Number(), and Boolean() constructors
var A = new String("Hello, world");
//this is not recommended or very useful
//you should also be carefull in creating these wrapper objects especially in comparisons
a == A; //true
a === A; //false - a typeof is "number" --- while A typeof is "object"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment