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.
The Primitive Data types in JavaScript include Number, String, Boolean, Undefined, Null and Symbol.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With