0

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
  • 2
    There's no real use case actually. The practical difference is that the string wrapper acts as an object (and for example can have own properties). Commented Jun 22, 2015 at 15:55

1 Answer 1

2

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"
    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.