Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the 'in' operator throwing an error with a string literal instead of logging false?

As per MDN the in operator returns true if the property exists and accordingly the first example logs true. But when using a string literal, why is it throwing an error instead of logging false?

let let1 = new String('test');  console.log(let1.length);  console.log('length' in let1)

var let1 = 'test';  console.log(let1.length);  console.log('length' in let1);
like image 441
brk Avatar asked Apr 04 '19 18:04

brk


People also ask

Why is string literal in Java?

Why Java uses the concept of String literal? To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

What is the difference when string is gets created using literal or new () operator?

When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.

Is False A string literal?

Answer. String literals are written by enclosing a set of characters within a pair of double quotes. A boolean literal can take only one of the two boolean values represented by the words true or false. String literals can be assigned to variables of String data type.


2 Answers

In a sense it is a matter of timing. String literals do not have any properties. The reason that you can call methods and lookup properties on primitive strings is because JavaScript automatically wraps the string primitive in a String object when a method call or property lookup is attempted. JavaScript does not interpret the in operator as a method call or property lookup so it does not wrap the primitive in an object and you get an error (because a string primitive is not an object).

See Distinction between string primitives and String objects

Also, the same docs referenced in your question specifically note that using in on a string primitive will throw an error.

You must specify an object on the right side of the in operator. For example, you can specify a string created with the String constructor, but you cannot specify a string literal.

like image 125
benvc Avatar answered Sep 23 '22 01:09

benvc


It throws an error because in is an operator for objects:

prop in object

but when you declare a string as `` (` string(template) literals) or "" '' (",' string literals) you don't create an object.

Check

typeof new String("x") ("object")

and

typeof `x` ("string").

Those are two different things in JavaScript.

like image 38
SkillGG Avatar answered Sep 22 '22 01:09

SkillGG