3

I’m studying JavaScript and this is a statement I came across:

new String("Hello");

This will create a new string that is the same as string literal "hello", although it will be classed as an object rather than a primitive values. For this reason it is preferable to use the string literal notation.

What is a String literal?

Why is new String("Hello") classed as Object?

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126

1 Answers1

1

A literal string (or literal <any data type>) means that you just reference the data directly.

For example

"Hello".length // returns 5

The "Hello" is a string literal since we are just referencing it "as-is". You could do exactly the same thing with a string object:

var strObj = new String("Hello");
strObj.length // returns 5

These two examples are pretty much identical (for the sake of this example). Both create a string variable and measure it's length. The first uses a string literal and the second uses a string object.


Here is another example using numbers - if you do a direct calculation such as:

5 + 2

you'll be using number literals - again, when you only reference the data directly, it is considered a "literal".

Lix
  • 47,311
  • 12
  • 103
  • 131