How do I determine if variable is undefined or null?
My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
But if I do this, the JavaScript interpreter halts execution.
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.
The standard way to catch null and undefined simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null.
Edit again
The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over.
You should not have any references to undeclared variables in your code.
Combining the above answers, it seems the most complete answer would be:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.
if (variable == null) {
// Do stuff, will only match null or undefined, this won't match false
}
if (typeof EmpName != 'undefined' && EmpName) {
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
Probably the shortest way to do this is:
if(EmpName == null) { /* DO SOMETHING */ };
Here is proof:
function check(EmpName) {
if(EmpName == null) { return true; };
return false;
}
var log = (t,a) => console.log(`${t} -> ${check(a)}`);
log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");
// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined"
And here are more details about == (source here)
BONUS: reason why === is more clear than == (look on agc answer)
jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element.
So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:
if (!EmpName) { //do something }
Edited answer: In my opinion, you shouldn't use the function from my below old answer. Instead, you should probably know the type of your variable and use the according to check directly (for example, wondering if an array is empty? just do if(arr.length===0){} etc.). This answer doesn't even answer OP's question.
I've come to write my own function for this. JavaScript is weird.
It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.
function empty(v) {
let type = typeof v;
if (type === 'undefined') {
return true;
}
if (type === 'boolean') {
return !v;
}
if (v === null) {
return true;
}
if (v === undefined) {
return true;
}
if (v instanceof Array) {
if (v.length < 1) {
return true;
}
} else if (type === 'string') {
if (v.length < 1) {
return true;
}
if (v === '0') {
return true;
}
} else if (type === 'object') {
if (Object.keys(v).length < 1) {
return true;
}
} else if (type === 'number') {
if (v === 0) {
return true;
}
}
return false;
}
TypeScript-compatible.
This function should do exactly the same thing like PHP's empty() function (see RETURN VALUES)
Considers undefined, null, false, 0, 0.0, "0" {}, [] as empty.
"0.0", NaN, " ", true are considered non-empty.
The shortest and easiest:
if(!EmpName ){
// DO SOMETHING
}
this will evaluate true if EmpName is:
null
undefined
NaN
empty
string ("")
0
false
If the variable you want to check is a global, do
if (window.yourVarName) {
// Your code here
}
This way to check will not throw an error even if the yourVarName variable doesn't exist.
Example: I want to know if my browser supports History API
if (window.history) {
history.back();
}
How this works:
window is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history doesn't exist then window.history returns undefined. undefined is falsey, so code in an if(undefined){} block won't run.
In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
Check all conditions:
if(variable === undefined || variable === null || variable === ''){
}
Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.
var s; // undefined
jQuery.isEmptyObject(s); // will return true;
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;
// usage
if(jQuery.isEmptyObject(s)){
alert('Either variable: s is undefined or its value is null');
}else{
alert('variable: s has value ' + s);
}
s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
I've just had this problem i.e. checking if an object is null.
I simply use this:
if (object) {
// Your code
}
For example:
if (document.getElementById("enterJob")) {
document.getElementById("enterJob").className += ' current';
}
You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).
if (x === null || x === undefined) {
// Add your response code here, etc.
}
source: https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
jQuery check element not null:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}
With the newest javascript changes, you can use the new logical operator ??= to check if the left operand is null or undefined and if so assign the value of right operand.
SO,
if(EmpName == null){ // if Variable EmpName null or undefined
EmpName = 'some value';
};
Is equivalent to:
EmpName ??= 'some value';
The easiest way to check is:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
I run this test in the Chrome console. Using (void 0) you can check undefined:
var c;
undefined
if (c === void 0) alert();
// output = undefined
var c = 1;
// output = undefined
if (c === void 0) alert();
// output = undefined
// check c value c
// output = 1
if (c === void 0) alert();
// output = undefined
c = undefined;
// output = undefined
if (c === void 0) alert();
// output = undefined
With the solution below:
const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);
console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...
I'm able to check for the following:
null
undefined
NaN
empty
string ("")
0
false
To test if a variable is null or undefined I use the below code.
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
if you create a function to check it:
export function isEmpty (v) {
if (typeof v === "undefined") {
return true;
}
if (v === null) {
return true;
}
if (typeof v === "object" && Object.keys(v).length === 0) {
return true;
}
if (Array.isArray(v) && v.length === 0) {
return true;
}
if (typeof v === "string" && v.trim().length === 0) {
return true;
}
return false;
}
(null == undefined) // true
(null === undefined) // false
Because === checks for both the type and value. Type of both are different but value is the same.
Let's look at this,
let apple; // Only declare the variable as apple
alert(apple); // undefined
In the above, the variable is only declared as apple. In this case, if we call method alert it will display undefined.
let apple = null; /* Declare the variable as apple and initialized but the value is null */
alert(apple); // null
In the second one it displays null, because variable of apple value is null.
So you can check whether a value is undefined or null.
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...
The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.
Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:
if (foo === void 0 || foo === null) { ... }
You can do something like this, I think its more efficient for multiple value check on the same variable in one condition
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
No one seems to have to posted this yet, so here we go:
a?.valueOf() === undefined works reliably for either null or undefined.
The following works pretty much like a == null or a == undefined, but it could be more attractive for purists who don't like == 😎
function check(a) {
const value = a?.valueOf();
if (value === undefined) {
console.log("a is null or undefined");
}
else {
console.log(value);
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
On a side note, a?.constructor works too:
function check(a) {
if (a?.constructor === undefined) {
console.log("a is null or undefined");
}
}
check(null);
check(undefined);
check(0);
check("");
check({});
check([]);
Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
You can only use second one: as it will check for both definition and declaration
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
I still think the best/safe way to test these two conditions is to cast the value to a string:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// Do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// Do something with your code
}
I like to use the !! in Javascript to ensure that a variable is set and that no error will be thrown.
However today I have a variable with 0 value that is valid for me. I need to ensure that it is not NaN nor undefined, is there really no short way to do it without the boring if (variable !== NaN && variable !== undefined?
If that may help, I am using angular.
Thx.
let a = 'value';
if (isNaN(a) || a == null) {
console.log('a is NaN or null, undefined');
} else {
// business logic ;)
}
To handle null also, caz isNaN(null) // false
You can use isNan. It will return true for undefined and NAN value but not for ZERO.
const variable = undefined;
if(isNaN(variable)){
console.log('I am undefined / NAN');
}else{
console.log('I am something / zero');
}
The correct way to check for undefined, null, NaN is
if(a == null || Number.isNaN(a)) {
// we did it!
}
please notice the use of Number.isNaN instead of just isNaN.
If you did use just isNaN then your check will not do what you want for values like strings or empty object
if(a == null || isNaN(a)) {
// {} comes in because `isNaN({})` is `true`
// strings that can't be coerced into numbers
// some other funny things
}
Read more at MDN
What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing) Then
End If
I need to convert this to javascript. Is that enough to check null?
This was my lead's answer, plz verify this,
if(typeof $(data).find("BigGroupType").text() != "undefined" && $(data).find("BigGroupType").text() != null) {
}
JavaScript has two values which mean "nothing", undefined and null. undefined has a much stronger "nothing" meaning than null because it is the default value of every variable. No variable can be null unless it is set to null, but variables are undefined by default.
var x;
console.log(x === undefined); // => true
var X = { foo: 'bar' };
console.log(X.baz); // => undefined
If you want to check to see if something is undefined, you should use === because == isn't good enough to distinguish it from null.
var x = null;
console.log(x == undefined); // => true
console.log(x === undefined); // => false
However, this can be useful because sometimes you want to know if something is undefined or null, so you can just do if (value == null) to test if it is either.
Finally, if you want to test whether a variable even exists in scope, you can use typeof. This can be helpful when testing for built-ins which may not exist in older browsers, such as JSON.
if (typeof JSON == 'undefined') {
// Either no variable named JSON exists, or it exists and
// its value is undefined.
}
You need to check for both null and undefined, this implicitly does so
if( oResponse.selectSingleNode("BigGroupType") != null ) {
}
It is the equivalent of:
var node = oResponse.selectSingleNode("BigGroupType");
if( node !== null &&
node !== void 0 ) {
}
void 0 being a bulletproof expression to get undefined
In JavaScript equvalent for Nothing is undefined
if(oResponse.selectSingleNode("BigGroupType") != undefined){
}
This logic:
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing)
Can be written like this in JavaScript:
if (typeof oResponse.selectSingleNode("BigGroupType") != 'undefined')
Nothing would equal undefined, but checking against undefined is not recommended for several reasons, it’s generally safer to use typeof.
However, if the selectSingleNode can return other falsy values such as null, it’s probably OK to just do a simple check if it is truthy:
if (oResponse.selectSingleNode("BigGroupType"))
JavaScript:-
(document.getElementById(“BigGroupType”) == undefined) // Returns true
JQuery:-
($(“#BigGroupType”).val() === “undefined”) // Returns true
Note in above examples undefined is a keyword in JavaScript, where as in JQuery it is just a string.
While looking at adding a trim function to the String prototype, I came across something that seems odd to me with JavaScript strings.
if (typeof console === 'undefined') {
var console = { };
console.log = function(msg) {
alert(msg)
}
}
function isString(str) {
return ((str && typeof str === 'string') ||
(str && (str.constructor == String && (str.toString() !== 'null' && str.toString() !== 'undefined'))));
}
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s*(\S*(?:\s+\S+)*)\s*$/, "$1");
};
}
function testing (str) {
if (isString(str)) {
console.log("Trimmed: " + str.trim() + " Length: " + str.trim().length);
} else {
console.log("Type of: " + typeof str);
}
return false;
}
function testSuite() {
testing(undefined);
testing(null);
testing("\t\r\n");
testing(" 90909090");
testing("lkkljlkjlkj ");
testing(" 12345 ");
testing("lkjfsdaljkdfsalkjdfs");
testing(new String(undefined)); //Why does this create a string with value 'undefined'
testing(new String(null)); //Why does this create a string with value 'null'
testing(new String("\t\r\n"));
testing(new String(" 90909090"));
testing(new String("lkkljlkjlkj "));
testing(new String(" 12345 "));
testing(new String("lkjfsdaljkdfsalkjdfs"));
}
Now I know that we shouldn't be creating Strings with the new operator, but I'd hate to have someone call this on an undefined or null string that was created more along the lines of:
new String ( someUndefinedOrNullVar );
What am I missing? Or is the !== 'null' && !== 'undefined' check really necessary (Removing that check, will show 'null' and 'undefined')?
From the ECMA standard:
9.8 ToString
The abstract operation ToString converts its argument to a value of type String according to Table 13
[ the table shows undefined converts to "undefined" and null to "null"]
...and then:
15.5.2.1 new String ( [ value ] )
The [[Prototype]] internal property of the newly constructed object is set to the standard built-in String prototype object that is the initial value of String.prototype (15.5.3.1).
The [[Class]] internal property of the newly constructed object is set to "String".
The [[Extensible]] internal property of the newly constructed object is set to true.
The [[PrimitiveValue]] internal property of the newly constructed object is set to ToString(value), or to the empty String if value is not supplied.
So since ToString(undefined) gives 'undefined', it makes sense.
I believe new String(null) and new String(undefined) return the value types which are strings: 'null' and 'undefined'.
Edit:
Actually, null is an object. But I think I'm right about undefined.
All objects in JavaScript can be cast to a string value, which is exactly what new String(null) does. The !== 'null' && !== 'undefined' check in this case is extreme foolproofing, although... the following all result in a string.
'' + null // 'null'
'' + undefined // 'undefined'
[null].join() // 'null'
But still imo. the extra foolproving is needless for trim(), heck, maybe someone actually has a string 'null' or 'undefined' or if not, would be great to see so you can debug it. Nay, remove the check!