Skip to content

Instantly share code, notes, and snippets.

@ivankisyov
Last active December 24, 2018 09:43
Show Gist options
  • Save ivankisyov/30d408b27db5898a22b6f5fd85a57088 to your computer and use it in GitHub Desktop.
Save ivankisyov/30d408b27db5898a22b6f5fd85a57088 to your computer and use it in GitHub Desktop.
Autoboxing in JS

Autoboxing in JS

// calling String function like this
// will try to create a primitive value of type string from the argument which 
// is passed to the String function
String("chair") // the result is "chair"
// calling String like this
// will create new wrapper object
const chairWrapperObject = new String("chair");
// result:
// {0: "c", 1: "h", 2: "a", 3: "i", 4: "r", length: 4}
// autoboxing:
let chairString = "chair";

chairString.length = 4;
// chairString is autoboxed, which means
// that a temp wrapper object is created, then its length property is retrived
// after that the wrapper object is removed!
// the original chairString is not affected!

Autoboxing will NOT work for the folloing primitive types:

  • null
  • undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment