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);
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).
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.
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.
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 theString
constructor, but you cannot specify a string literal.
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.
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