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!

Community
  • 1
  • 1
GniruT
  • 731
  • 1
  • 6
  • 14
  • 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 07 '15 at 15:02

2 Answers2

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.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
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".

Philipp
  • 67,764
  • 9
  • 118
  • 153