JavaScript checking for null vs. undefined and difference between == and ===
How do I check a variable if it's
null
orundefined
...
Is the variable null
:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a
is undefined
.
Is it undefined
:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a
is null
.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the
null
andundefined
?
They're both values usually used to indicate the absence of something. undefined
is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined
; there's a difference between calling a function with the value undefined
for an argument, and leaving that argument off entirely.)
null
is slightly more specific than undefined
: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null
, not undefined
. And similarly, the DOM's getElementById
operation returns an object reference — either a valid one (if it found the DOM element), or null
(if it didn't).
Interestingly (or not), they're their own types. Which is to say, null
is the only value in the Null type, and undefined
is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that ==
will do type coercion to try to get the values to match, and ===
won't. So for instance "1" == 1
is true, because "1"
coerces to 1
. But "1" === 1
is false, because the types don't match. ("1" !== 1
is true.) The first (real) step of ===
is "Are the types of the operands the same?" and if the answer is "no", the result is false
. If the types are the same, it does exactly what ==
does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0
is true).
More in the spec:
- Abstract Equality Comparison (
==
, also called "loose" equality) - Strict Equality Comparison (
===
)
What is the difference between null and undefined in JavaScript?
undefined
means a variable has been declared but has not yet been assigned a value :
var testVar;
alert(testVar); //shows undefined
alert(typeof testVar); //shows undefined
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
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.
How to check for an undefined or null variable in JavaScript?
You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:value = obj.prop || defaultValue
which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue
Can someone explain this simple concept of null and undefined, more specifically single double & triple equals, or can you link the best explanation
== converts the variable values to the same type before performing the actual comparison(making type coercion)
=== doesn't do type coercion and returns true only if both values and types are identical for the two variables being compared.
Let's take a look at some examples:
console.log(5 == "5"); // no type coercion is being made - hence, the result is true.
console.log(5 === "5"); // type coercion is being made, value is the same but the data types are not (number vs string);
console.log(undefined == null); // should be true because type coercion is not being made and the data values are both falsy!
console.log(undefined !== null); // should be true cause type coercion is being made and the data types are differnt!
console.log(undefined === null); // // should be false cause type coercion is being made and the data types are differnt.
console.log(undefined != null); // should be false cause type coercion is not being made and the data values are both falsy!
Is there any function difference between using != null and != undefined in javascript?
There is no difference as you can see in below table for JS ==
testing (focus on null/undefined row/column) (src: here). So myVar!=null
is true only if myVar
value is not null
and not undefined
(same with myVar != undefined
)
It looks like both has similar performance (I made test on Mac OS X 10.13.4 HighSierra: Chrome 71.0.3578, Firefox 65.0.0 and Safari 11.1.0 - you can run test in your browser here)
let myVar1=null;
let myVar2=undefined;
What is the difference between null and undefined in JavaScript?
undefined
means a variable has been declared but has not yet been assigned a value :
var testVar;
alert(testVar); //shows undefined
alert(typeof testVar); //shows undefined
Checking for null or undefined
Also, I know that
if (value == null) {
}
Will get the job done 90% of the time, unless value is zero... or false... or a number of implicit things that can cause obscure bugs.
No, it gets the job done 100% of the time. The only values that are == null
are null
and undefined.
0 == null
is false. "" == undefined
is false. false == null
is false. Etc. You're confusing == null
with falsiness, which is a very different thing.
That's not to say, though, that it's a good idea to write code expecting everyone to know that. You have a perfectly good, clear check in the code you're already using. Whether you choose to write value == null
or the explicit one you're currently using (or if (value === undefined || value === null)
) is a matter of style and in-house convention. But value == null
does do what you've asked: Checks that value
is null
or undefined
.
The details of ==
are here: Abstract Equality Comparison.
How can I determine if a variable is 'undefined' or 'null'?
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
.
Related Topics
Firing Event on Dom Attribute Change
How to Dodge Jquery Promises Completely When Chaining Two Async Jquery Functions
JavaScript Tofixed Not Rounding
Why Does (0 < 5 < 3) Return True
Fast Rectangle to Rectangle Intersection
How to Access Shadow Dom Elements Through the Parent Document
How to Export HTML Table to Excel Using JavaScript
Capture Frames from Video with HTML5 and JavaScript
Difference Between Element.Value and Element.Getattribute("Value")
How Does Basic Object/Function Chaining Work in JavaScript
Unexpected Token Colon JSON After Jquery.Ajax#Get
How to Change Href of <A> Tag on Button Click Through JavaScript
How to Record Webcam and Audio Using Webrtc and a Server-Based Peer Connection
How to Get the HTML for a Dom Element in JavaScript
Trigger Standard HTML5 Validation (Form) Without Using Submit Button