49 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
When either the equality operator in a test for ``++null++`` or ``++undefined++``, or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced only if it is ``++null++``/``++undefined++``, leading to a guaranteed ``++TypeError++``.
2020-06-30 12:47:33 +02:00
== Noncompliant Code Example
----
if (str == null && str.length == 0) {
console.log("String is empty");
}
if (str == undefined && str.length == 0) {
console.log("String is empty");
}
if (str != null || str.length > 0) {
console.log("String is not empty");
}
if (str != undefined || str.length > 0) {
console.log("String is not empty");
}
----
== Compliant Solution
----
if (str != null && str.length == 0) {
console.log("String is empty");
}
if (str != undefined && str.length == 0) {
console.log("String is empty");
}
if (str == null || str.length > 0) {
console.log("String is not empty");
}
if (str == undefined || str.length > 0) {
console.log("String is not empty");
}
----
ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::rspecator-view[]