Length in line "string" and length in new line ("string")

Why:

var a = "string";
console.log("length" in a);

      

Gives an error

var b = new String("string");
console.log("length" in b);

      

Gives true.

a has the same property length as b. typeof is a string, but also an object with its own properties. MDN says:

JavaScript automatically converts primitives to String objects, so you can use String object methods on primitive strings.

What happened?

+3


source to share


2 answers


The keyword in

only works with objects.

var a = 'foo';
var b = new String(a);

console.log(typeof a);  // "string"
console.log(typeof b);  // "object"

      

Read the documentation about the difference between string primitives and string objects



The following code will automatically convert the primitive to an object when accessing a property, in this case length

.

console.log("string".length);

      

+1


source


b is a String object, but a is not, it is a string. If you try a.isPrototypeOf (String) it should output false



0


source







All Articles