0

I'm reading about the difference between String literal and String objects. See What is the difference between string literals and String objects in JavaScript?

But I'm a bit confuse because there it's explained that you can use methods of the String Objects but technically is a String literal an String Object? I'm not asking if we can use the same methods, only if a String literal is an object. Thanks!

1
  • NO, string is not object, but for consistency, Javascript lets us use it as if it is an Object. When invoking a method on string it is boxed in String object.
    – Tushar
    Oct 7, 2015 at 15:02

2 Answers 2

3

The term "string literal" refers to a syntactic convention for representing string values directly in code.

The code

"Hello Everyone"

is a string literal for a string with 14 characters.

The value represented by a string literal is a string primitive. It is not an object. That's why if you use:

typeof "Hello Everyone"

this will return the value "string", not "object".

JavaScript allows boxing of any string primitive to promote them to string objects under certain circumstances. Attempting to call a method on a string value is one of these circumstances. So if you call:

"Hello Everyone".toUpperCase()

the value represented by this literal will be boxed into a string Object, and the method will be called on that object.

1
  • thank you very much for the clear answer :)
    – GniruT
    Oct 7, 2015 at 15:23
0

You can check the type of a Javascript variable with the typeof operator. typeof "Hello World" and typeof String("Hello World") both return the type "string".

Also, a strict-equal check "Hello" === String("Hello") returns true, which means that they are not just value-equal but type-equal.

However, typeof new String("Hello World") returns "object".

Not the answer you're looking for? Browse other questions tagged or ask your own question.