Property value of a String object in JavaScript-Collection of common programming errors

There are two different types of Strings and the behave quite differently. A literal is created just by using quotes around your string. An object is created by implicit use of the new keyword. If you assign a string to a variable using the String keyword, without the new keyword the contents of the parenthesis will be cast as a string literal.

A string literal has access to all of a string’s objects and methods because javascript will temporarily cast a string literal as a string object in order to run the desired method.

Where the two differ is their treatment of new properties and methods. Like all Javascript Objects you can assign properties and methods to any String object.

You can not add properties or methods to a string literal. They are ignored by the interpreter.

The reason you can’t add properties or methods to a string literal is that when you try to access a literal’s property or method, the Javascript interpreter temporarily copies the value of the string into a new object and then use that object’s properties or methods. This means a String literal can only access a string’s default properties or methods and those that have been added as prototypes.

Originally posted 2013-11-09 22:55:21.