Home  >  Article  >  Web Front-end  >  How Can I Reliably Check for Null or Undefined Variables in JavaScript?

How Can I Reliably Check for Null or Undefined Variables in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 17:08:02853browse

How Can I Reliably Check for Null or Undefined Variables in JavaScript?

Exploring Reliable Null and Undefined Variable Detection in JavaScript

In JavaScript, ascertaining whether a variable is defined or has a value can be a recurring task. Many developers resort to the following pattern:

<code class="javascript">if (typeof(some_variable) != 'undefined' && some_variable != null) {
    // Do something with some_variable
}</code>

While this method is reliable, it can be verbose. Some sources suggest that simply checking if the variable exists has the same effect:

<code class="javascript">if (some_variable) {
    // Do something with some_variable
}</code>

However, certain development environments, such as Firebug, report an error when some_variable is undefined with the second approach.

A more efficient way to check for null or undefined variables is to utilize the following syntax:

<code class="javascript">if (some_variable == null) {
    // some_variable is either null or undefined
}</code>

This alternative is equivalent to the verbose version and is also supported by development tools like Firebug.

Notes:

  1. The variable must be declared before using this shorthand technique; otherwise, a ReferenceError will occur. However, it can be safely used for optional arguments or object property checks.
  2. A different but not equivalent variant of this check includes variables that are 0, NaN, false, or empty strings:
<code class="javascript">if (!some_variable) {
    // some_variable is either null, undefined, 0, NaN, false, or an empty string
}</code>
  1. Using strict equality checks (===) is generally preferred over ==. However, the recommended == null comparison is an exception to this rule.

Update 2021-03:

Modern browsers support the Nullish coalescing operator (??) and Logical nullish assignment (??=), providing a concise way to assign default values if variables are null or undefined:

<code class="javascript">if (a.speed == null) {
    // Set default if null or undefined
    a.speed = 42;
}</code>

This can be rewritten using the Nullish coalescing operator:

<code class="javascript">a.speed ??= 42;</code>

The above is the detailed content of How Can I Reliably Check for Null or Undefined Variables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn