Why are there two kinds of JavaScript strings?

There are two types of strings in Javascript — literal strings and String objects. They do behave a little differently. The main difference between the two is that you can add additional methods and properties to a String object. For instance:

var strObj = new String("object mode");
strObj.string_mode = "object"
strObj.get_string_mode = function() { return this.string_mode; }

// this converts it from an Object to a primitive string:
str = strObj.toString();

A string literal is just temporarily cast to a String object to perform any of the core methods.

The same kinds of concepts apply to other data types, too. Here’s more on primitive data types and objects.

EDIT

As noted in the comments, string literals are not primitive strings, rather a “literal constant whose type is a built-in primitive [string] value”, citing this source.

Leave a Comment