2023-07-26 16:00:44 +02:00

69 lines
2.6 KiB
Plaintext

== Why is this an issue?
In JavaScript, `null` and `undefined` are primitive values that do not have properties or methods. When accessing a property on a `null` or `undefined` value, JavaScript tries to access the property of an object that does not exist, which results in a `TypeError`.
This can cause the program to crash or behave unexpectedly, which can be difficult to debug.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
let foo = null;
console.log(foo.bar); // Noncompliant: TypeError will be thrown
----
Use the logical AND operator (`&&`) to check if a variable is truthy before attempting to access its properties. The expression will short-circuit and return the falsy value instead of attempting to access its properties.
[source,javascript,diff-id=1,diff-type=compliant]
----
let foo = null;
console.log(foo && foo.bar);
----
Alternatively, use the optional chaining operator (`?.`) to check if the variable is `null` or `undefined` before attempting to access its property. This operator is more readable and concise, especially when dealing with nested properties.
[source,javascript,diff-id=1,diff-type=compliant]
----
let foo = null;
console.log(foo?.bar);
----
== Resources
=== Documentation
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined[MDN - `undefined`]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null[MDN - `null`]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError[MDN - `TypeError`]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/No_properties[MDN - TypeError: "x" has no properties]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining[MDN - Optional chaining (``++?.++``)]
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND[MDN - Logical AND (``++&&++``)]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
=== on 15 Mar 2016, 09:45:14 Pierre-Yves Nicolas wrote:
Useful links:
* \https://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/
* \https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined
We could make this rule also cover invalid function calls, e.g.:
----
var x = 42;
x(); // Noncompliant: TypeError will be thrown
----
However, there may be some overlap with RSPEC-2999.
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]