53 lines
1.8 KiB
Plaintext
53 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In JavaScript, the ``++in++`` operator is primarily used to check if a property exists in an object or if an index exists in an array. However, it is not suitable for use with primitive types such as numbers, strings, or booleans because they are not objects and do not have properties.
|
|
|
|
If the right operand is of primitive type, the ``++in++`` operator raises a ``++TypeError++``.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
let x = "Foo";
|
|
"length" in x; // Noncompliant: TypeError
|
|
0 in x; // Noncompliant: TypeError
|
|
"foobar" in x; // Noncompliant: TypeError
|
|
----
|
|
|
|
You should use the object equivalents of numbers, strings, or booleans if you really want to check property existence with the ``++in++`` operator.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
let x = new String("Foo");
|
|
"length" in x; // true
|
|
0 in x; // true
|
|
"foobar" in x; // false
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in[in operator]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Glossary/Primitive[Primitive]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number[Number() constructor]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String[String() constructor]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/Boolean[Boolean() constructor]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
TypeError can be thrown as this operand might have primitive type.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
Primary: The right operand.
|
|
|
|
Secondary: the operator.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|