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
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:
(This is somewhat to my surprise; most things that require an object coerce primitives to objects, but not in
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With