Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in these 2 Strings (JavaScript)

I was trying to create string data-types variables with values in 2 ways.

  1. As string-literal
  2. Using New Keyword

But to me it seems that these both are different in representation on console.log. Can someone tell me if 2nd way doesn't return string or is it someway different?

var str1 = "abc";
var str2 = new String("def");
console.log(str1);
console.log(str2);

Expected:

abc, def

Output:

enter image description here

like image 994
Deadpool Avatar asked Sep 07 '20 05:09

Deadpool


2 Answers

JavaScript has two main type categories, primivites and objects.

typeof new String(); // "object"
typeof '';           // "string"

For statements of assigning primitive values to a variable like:

var str1 = "Hi";

JavaScript will internally create the variable using:

String("Hi")

Using the new keyword works differently and returns an object instead.

like image 79
xMayank Avatar answered Oct 22 '22 15:10

xMayank


Calling new String(something) makes a String instance object.

The results look the same via console.log() because it'll just extract the primitive string from the String instance you pass to it.

So: just plain String() returns a string primitive. new String('xyz') returns an object constructed by the String constructor.

It's rarely necessary to explicitly construct a String instance.

like image 4
Gaurav Mogha Avatar answered Oct 22 '22 15:10

Gaurav Mogha