Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript and String as primitive value

Tags:

javascript

In JavaScript a String is a primitive value. But is also a String object... A primitive value is a value put directly into a variable.

So my question is:

var d = "foo";

does d contain directly foo or a reference to a string object like other languages?

Thanks.

like image 961
xdevel2000 Avatar asked Feb 15 '12 07:02

xdevel2000


People also ask

Is string in JavaScript primitive?

The Primitive Data types in JavaScript include Number, String, Boolean, Undefined, Null and Symbol.

Is a string a primitive data type?

The string data type is a non-primitive data type but it is predefined in java, some people also call it a special ninth primitive data type. This solves the case where a char cannot store multiple characters, a string data type is used to store the sequence of characters.

Should strings be primitive?

Definitely, String is not a primitive data type. It is a derived data type. Derived data types are also called reference types because they refer to an object.


2 Answers

If I understand it correctly, d will contain the string literal "foo", and not a reference to an object. However, the JavaScript engine will effectively cast the literal to an instance of String when necessary, which is why you can call methods of String.prototype on string literals:

"some string".toUpperCase(); //Method of String.prototype

The following snippet from MDN may help to explain it further (emphasis added):

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives and String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

This is all explained in detail in the specification, but it's not exactly easy reading. I asked a related question recently (about why it is possible to do the above), so it might be worth reading the (very) detailed answer.

like image 98
James Allardice Avatar answered Oct 12 '22 22:10

James Allardice


if you define

var d = "foo";

than d contains directly foo but, if you define

var S = new String("foo");

then S is an Object

Example:

var s1 = "1";
var s2 = "1";
s1 == s2 -> true
var S1 = new String("2");
var S2 = new String("2");
S1 == S2 -> false
like image 20
belykh Avatar answered Oct 12 '22 22:10

belykh