Difference between string primitive and string wrapper object in Javascript

1.3k views Asked by At

I'm very confused about what the wrapper objects for primitives. For example, a string primitive and a string created with the string wrapper object.

var a = "aaaa";
var b = new String("bbbb");
console.log(a.toUpperCase()); // AAAA
console.log(b.toUpperCase()); // BBBB
console.log(typeof a);        // string
console.log(typeof b);        // object

Both give access to String.prototype methods, and seem to act just like a string literal. But one is not a string, it's an object. What is the practical difference between a and b? Why would I create a string using new String()?

1

There are 1 answers

0
Oriol On

A primitive string is not an object. An object string is an object.

Basically, that means:

  • Object strings are compared by reference, not by the string they contain

    "aaa" === "aaa";                         // true
    new String("aaa") === new String("aaa"); // false
    
  • Object strings can store properties.

    function addProperty(o) {
      o.foo = 'bar'; // Set a property
      return o.foo;  // Retrieve the value
    }
    addProperty("aaa");             // undefined
    addProperty(new String("aaa")); // "bar"