Best practice checking if a variable is undefined

I had some problems in my conditions regarding undefined variables. What if to summarize this, the best way to check if a variable is undefined?

I mostly fought with

x === undefined 

and

 typeof x === 'undefined' 
+6
source share
4 answers

You can use both methods to check if the value is undefined . However, there are few nuances that you need to know about.

The first approach uses the comparison operator === to compare with an undefined type :

 var x; // ... x === undefined; // true 

This will work as expected only if the variable is declared but not defined, i.e. is undefined , which means you have var x somewhere in your code, but it has never been assigned a value. So undefined by definition.

But if the variable is not declared with the var keyword, the above code will cause a reference error:

 x === undefined // ReferenceError: x is not defined 

In such situations, typeof comparison is more reliable:

 typeof x == 'undefined' // true 

which will work correctly in both cases: if the variable has never been assigned a value, and if its value is really undefined .

+9
source
 x === undefined 

does not work if the variable is not declared. This returns true only if the variable is declared but not defined.

Better to use

typeof x === 'undefined'

+1
source

You can use any of them. If you want to check if there is an undefined or null variable that you could use:

 x == null 

The result is true if x is undefined or null.

0
source

I think both, depending on what you are testing? If this property, I would always use x === undefined , as it is more understandable (and seems to be faster).

As others have said, x === undefined will not work if x is not declared. Personally, I think this is an even better reason to use it, since I usually should not check if a variable is declared at all - this is usually a sign of an encoding error.

I saw a lot of other version for testing arguments - f = function(x) {if (typeof x == 'undefined') …} - if I have code to check the code like this, I will tell them to change it. We know that a variable is declared, and creating the habit of writing it in this way increases the likelihood that you will spend time trying to chase typo errors.

The main exception is when you try to check if a component or library is loaded or initialized correctly. if (typeof jQuery == 'undefined') … makes sense. But in the medium term, all this should become a module in any case, and in this case, a type test should, in my opinion, be phased, as harmful.

(In addition, I personally prefer if (window.jQuery === undefined) for this case. However, it is not portable for isomorphic code.)

0
source

Source: https://habr.com/ru/post/982675/


All Articles