They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
nullundefined0""(the empty string)falseNaN
They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
nullundefined0""(the empty string)falseNaN
Here is how you can test if a variable is not NULL:
if (myVar !== null) {...}
the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..
Hi, all, I often do stuff like this in my code, to check for a variable being not null and not undefined.
// check if value is not null and not undefined
if (value) {
...
}However, I'm now thinking this can leads to bugs, because of 0, "", false and NaN also being falsy.
What is a better way to check a variable is not null and not undefined? I could use this I think, wondering if there is something shorter than this:
if (typeof value !== 'undefined' || value !== null) {
...
}Videos
Is null false in JavaScript?
What is a null check?
What is a strict null check?
this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.
1. Strict Not Version
if (val !== null) { ... }
The Strict Not Version uses the Strict Equality Comparison Algorithm. The !== operator has faster performance than the != operator, because the Strict Equality Comparison Algorithm doesn't typecast values.
2. Non-strict Not Version
if (val != null) { ... }
The Non-strict Not Version uses the Abstract Equality Comparison Algorithm. The != operator has slower performance than the !== operator, because the Abstract Equality Comparison Algorithm typecasts values.
3. Double Not Version
if (!!val) { ... }
The Double Not Version has faster performance than both the Strict Not Version and the Non-Strict Not Version. However, the !! operator will typecast "falsey" values like 0, '', undefined and NaN into false, which may lead to unexpected results, and it has worse readability because null isn't explicitly stated.
JavaScript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!pass || !cpass || !email || !cemail || !user){
Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN.
Please note that if you are specifically checking for numbers, it is a common mistake to miss 0 with this method, and num !== 0 is preferred (or num !== -1 or ~num (hacky code that also checks against -1)) for functions that return -1, e.g. indexOf).
To check for null SPECIFICALLY you would use this:
if (variable === null)
This test will ONLY pass for null and will not pass for "", undefined, false, 0, or NaN.
Additionally, I've provided absolute checks for each "false-like" value (one that would return true for !variable).
Note, for some of the absolute checks, you will need to implement use of the absolutely equals: === and typeof.
I've created a JSFiddle here to show all of the individual tests working
Here is the output of each check:
Null Test:
if (variable === null)
- variable = ""; (false) typeof variable = string
- variable = null; (true) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Empty String Test:
if (variable === '')
- variable = ''; (true) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Undefined Test:
if (typeof variable == "undefined")
-- or --
if (variable === undefined)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (true) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
False Test:
if (variable === false)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (true) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (false) typeof variable = number
Zero Test:
if (variable === 0)
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (true) typeof variable = number
- variable = NaN; (false) typeof variable = number
NaN Test:
if (typeof variable == 'number' && !parseFloat(variable) && variable !== 0)
-- or --
if (isNaN(variable))
- variable = ''; (false) typeof variable = string
- variable = null; (false) typeof variable = object
- variable = undefined; (false) typeof variable = undefined
- variable = false; (false) typeof variable = boolean
- variable = 0; (false) typeof variable = number
- variable = NaN; (true) typeof variable = number
As you can see, it's a little more difficult to test against NaN;
You can just check if the variable has a truthy value or not. That means
if (value) {
// do something..
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance
if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.
This question has two interpretations:
Check if the variable has a value
Check if the variable has a truthy valueThe following answers both.
In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:
โญโ nullish โโโโโโโฎ โญโ not nullish โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โโโโโโโโโโโโโฌโโโโโโโฌโโโโโโโโฌโโโโฌโโโโโฌโโโโโโฌโโโโโโโฌโโโโฌโโโโโโโโโโฌโโโโโโ
โ undefined โ null โ false โ 0 โ "" โ ... โ true โ 1 โ "hello" โ ... โ
โโโโโโโโโโโโโดโโโโโโโดโโโโโโโโดโโโโดโโโโโดโโโโโโดโโโโโโโดโโโโดโโโโโโโโโโดโโโโโโ
โฐโ falsy โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ โฐโ truthy โโโโโโโโโโโโโโโโฏ
Check if value is nullish (undefined or null)
Use one of the following depending on your coding style:
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }
Notes:
- The
==operator works because it has a special case for null vs undefined comparison - The
===operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately - The first and third examples work identically, however the third one is rarely seen in production code
- The fourth example uses nullish coalescing operator to change nullish values to
nullfor straight forward comparison
Check if value is not nullish
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }
Check if value is falsy
Use the ! operator:
if (!value) { /* value is falsy */ }
Check if value is truthy
if (value) { /* value is truthy */ }
Data validation
The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:
/*
* check if value is greater than/equal to 0
* note that we cannot use truthy check here because 0 must be allowed
*/
[null, -1, 0, 1].forEach(num => {
if (num != null && num >= 0) {
console.log("%o is not nullish and greater than/equal to 0", num);
} else {
console.log("%o is bad", num);
}
});
/*
* check if value is not empty-or-whitespace string
*/
[null, "", " ", "hello"].forEach(str => {
if (str && /\S/.test(str)) {
console.log("%o is truthy and has non-whitespace characters", str);
} else {
console.log("%o is bad", str);
}
});
/*
* check if value is not an empty array
* check for truthy before checking the length property
*/
[null, [], [1]].forEach(arr => {
if (arr && arr.length) {
console.log("%o is truthy and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
/*
* check if value is not an empty array
* using optional chaining operator to make sure that the value is not nullish
*/
[null, [], [1]].forEach(arr => {
if (arr?.length) {
console.log("%o is not nullish and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});
If you truly want to confirm that a variable is not null and not an empty string specifically, you would write:
if(data !== null && data !== '') {
// do something
}
Notice that I changed your code to check for type equality (!==|===).
If, however you just want to make sure, that a code will run only for "reasonable" values, then you can, as others have stated already, write:
if (data) {
// do something
}
Since, in javascript, both null values, and empty strings, equals to false (i.e. null == false).
The difference between those 2 parts of code is that, for the first one, every value that is not specifically null or an empty string, will enter the if. But, on the second one, every true-ish value will enter the if: false, 0, null, undefined and empty strings, would not.
Instead of using
if(data !== null && data !== '' && data!==undefined) {
// do something
}
You can use below simple code
if(Boolean(value)){
// do something
}
- Values that are intuitively โemptyโ, like 0, an empty string, null, undefined, and NaN, become false
- Other values become true