When is a string an object when using the in operator?

Why is this:

console.log('length' in new String('test'))

return true , whereas this:

console.log('length' in String('test'))

throw a TypeError?

Cannot use "in" operator to search for "length" in test

+4
source share
4 answers

JavaScript has string primitives and string objects. (And similarly for numbers and Booleans.) In your first test, you test an object because it new String()creates an object. The second time you test the primitive, because it String(x)simply converts xto a string. The second test is exactly the same as the recordconsole.log('length' in 'test');

in ( ) , -, ; RelationalExpression: RelationalExpression in ShiftExpression:

  1. (rval) , TypeError.

(, , , , in.)

+2

Try:

typeof String('test') -> "string"
typeof new String('test') -> "object"

in .

+2

MDN

in true, . in. , , String, .

var color1 = new String("green");
"length" in color1 // returns true

var color2 = "coral";
// generates an error (color2 is not a String object)
"length" in color2
+2
var s_prim = 'foo'; //this return primitive
var s_obj = new String(s_prim);//this return String Object

console.log(typeof s_prim); // Logs "string"
console.log(typeof s_obj);  // Logs "object"

MDN

The in operator returns true if the specified property is in the specified object.

   "length" in s_obj // returns true       

   "length" in s_prim // generates an error (s_prim is not a String object)

The operator is used only for objects, arrays

+2
source

Source: https://habr.com/ru/post/1649287/


All Articles