Unboxing

If you have an object wrapper and you want to get the underlying primitive value out, you can use the valueOf() method:

  1. var a = new String( "abc" );
  2. var b = new Number( 42 );
  3. var c = new Boolean( true );
  4. a.valueOf(); // "abc"
  5. b.valueOf(); // 42
  6. c.valueOf(); // true

Unboxing can also happen implicitly, when using an object wrapper value in a way that requires the primitive value. This process (coercion) will be covered in more detail in Chapter 4, but briefly:

  1. var a = new String( "abc" );
  2. var b = a + ""; // `b` has the unboxed primitive value "abc"
  3. typeof a; // "object"
  4. typeof b; // "string"