Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why does 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

like image 411
Pierre Arlaud Avatar asked Feb 07 '23 12:02

Pierre Arlaud


1 Answers

JavaScript has string primitives and string objects. (And similarly for numbers and booleans.) In your first test, you're testing an object, because new String() creates an object. In your second, you're testing a primitive, because String(x) just converts x to string. Your second test is exactly the same as writing console.log('length' in 'test');

The in operator (you have to scroll down a bit) throws a type error if you use it on something that isn't an object; it's the fifth of six steps under RelationalExpression : RelationalExpression in ShiftExpression:

  1. If Type(rval) is not Object, throw a TypeError exception.

(This is somewhat to my surprise; most things that require an object coerce primitives to objects, but not in.)

like image 118
T.J. Crowder Avatar answered Feb 09 '23 05:02

T.J. Crowder