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
}
Lets say I have array something like this:
$game = Array
(
['round'] => Array
(
['match'] => Array
(
['player_2'] => Array
(
[name] => asddd
[id] => 1846845
[winner] => yes
)
['player_21'] => Array
(
[name] => ddd
[id] => 1848280
[winner] => no
)
)
)
)
And lets say in Node.js/Javascript I need to check if player_3 winner key value is yes. In PHP, you did something like this:
if( $game['round']['match'][player_3]['winner'] == 'yes'){
}
Because there is no player_3 it returns false in PHP, but if I did something similar in Javascript:
if( typeof game['round']['match'][player_3]['winner'] != 'undefined' && game['round']['match'][player_3]['winner'] == 'yes'){
}
I would get error: (node:15048) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined, because player_3 doesn't exist in array and you can't check key value of array, that doesn't exist.
You could do this in Javascript:
if(
typeof game['round'] != 'undefined' &&
typeof game['round']['match'] != 'undefined' &&
typeof game['round']['match']['player_3'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] == 'yes'
){
var playerIsWinner = true;
}else{
var playerIsWinner = false;
}
You check each array inside array from top down and make sure that they exists. I don't know if it actually works, but even if it does, it seems bad and stupid way to check something. I mean look how simple it is in PHP, while in Javascript I have to check each array existence inside array. So is there better way checking value of array?
Please, look at the lodash library, especially at methods, such as get. Then you may safely try something like:
_.get(game, 'round.match.player3.winner', false);
That's it :)
The array you've shown resembles more of an object in JS. So here's what you could possibly try.
const obj = {
round: {
match: {
player_2: {
name: 'asddd',
id: 1846845,
winner: true
},
player_21: {
name: 'ddd',
id: 1848280,
winner: false
}
}
}
}
...
const isWinner = (key) => {
try {
return obj.round.match[key].winner
} catch(e) {
return false
}
}
console.log(isWinner('player_2'))
By wrapping your return inside of try ... catch, you prevent the error from being thrown at your query and possibly stopping the app from continuing on. If from whatever reason the structure of your object would change, you'd still have a boolean value returned.
If you have to keep your winner value in form of a string, you could simply compare the value, and you'll end up with boolean as a result. As so:
const isWinner = (key) => {
try {
return (obj.round.matchs[key].winner === 'yes')
} catch(e) {
return false
}
}
No you don't need to do manual check for deeply nested data for null or undefined, instead you could rollout your own small but compact function in this case get and be flexible with any input data provided. See more about Array.prototype.reduce()
// this single line will do the trick
const get = (p, o) =>p.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, o)
// let's pass in our props object...
const props = {"round":{"match":[{"player_21":{"name":"asdfg","id":1846845,"winner":"not yet"}},{"player_2":{"name":"sany","id":1846280,"winner":"no"}},{"player_3":{"name":"sunny","id":1846000,"winner":"yes"}}]}}
var playerIsWinner = false;
//console.log(get(['round', 'match', 2, 'player_3', 'winner'], props))
if (get(['round', 'match', 2, 'player_3', 'winner'], props) == 'yes') {
playerIsWinner = true;
}
console.log(playerIsWinner)
You can do the following to avoid the undefined error:
if ( game['round']['match'][player_3] && game['round']['match'][player_3]['winner'] == 'yes' ) {
...
}
Because undefined is "falsey" you'll get false instead of undefined if player_3 does not exist, and true if player_3 exists and is the winner.
Just wrap in a try catch block. This allows you to skip all of your boilerplate typeof statements:
typeof game['round'] != 'undefined' &&
typeof game['round']['match'] != 'undefined' &&
typeof game['round']['match']['player_3'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] != 'undefined' &&
typeof game['round']['match']['player_3']['winner'] == 'yes'
Instead throw an error and handle it if a element is not present. For example:
let nestedObj = {
prop1: {
propa1: {
propb1: 'test'
}
},
prop2: {}
}
try {
console.log(nestedObj['prop1']['propa1']['propb1']);
console.log(nestedObj['prop2']['propa2']['propb2']);
} catch(e) {
console.log('prop not defined');
}
This is a lot simpler than checking for every simple condition like you are doing now.
I'm trying to figure out how to check if a deeply nested JSON object, with several unknown arrays and properties contains a property that I'm looking for. I'm looking for a property that is called "isInvalid". If the field is there and the value of that key is true. I want to return false.
var checkValidity = function (data) {
for (var property in data) {
if (data.hasOwnProperty(property)) {
if (property == "isInvalid" && data[property] === true) {
return false;
}
else {
if (typeof data[property] === "object" && data[property] !== null) {
this.checkValidity(data[property]);
}
}
}
}
};
This is the code I've been trying out but I'm unable to get that to work. I have been looking into underscore also, but cant find the needed functions. Anyone has an idea? (No reg exp please)
If you really just want to check for property presence regardless of its particular location within JSON, then the easiest/fastest way is substring search in the source JSON string. If the latter is well-formed, then the property should be encoded in JSON as '"isInvalid":true'.
var checkValidity = function (jsonstr) {
return jsonstr.indexOf('"isInvalid":true') >= 0;
}
You can check like this
var s = {a:'1',b:'2'};
if(Object.getOwnPropertyNames(s).indexOf('a') != -1){
console.log('available');
}else{
console.log('Not available');
};
editing answer... UPDATE
var s = {
a1: '1',
b: '2',
c: {
a: '11'
}
};
var checkValidity = function (data) {
if (Object.getOwnPropertyNames(data).indexOf('a') != - 1) {
console.log('Found that key!!!');
} else {
for (var property in data) {
if (Object.getOwnPropertyNames(property).indexOf('a') != - 1) {
console.log('Found that key!!!');
} else {
if (typeof data[property] === 'object' && data[property] !== null) {
console.log('not found continue in inner obj..');
this.checkValidity(data[property]);
}
}
}
};
};
checkValidity(s);
It tests for every nesting level the property isInvalid and if not, all other properties as object and their content. Array#every breaks if one return is false.
function checkValidity(data) {
return !data.isInvalid && Object.keys(data).every(function (property) {
if (typeof data[property] === "object" && data[property] !== null) {
return checkValidity(data[property]);
}
return true;
});
}
var data = {
a: 1,
b: 2,
c: {
isInvalid: true,
a: false
}
};
document.write('checkValidity() should be false: ' + checkValidity(data) + '<br>');
data.c.isInvalid = false;
document.write('checkValidity() should be true: ' + checkValidity(data));
For complex json searching like this, I would use jsonpath ( http://goessner.net/articles/JsonPath/ ) which is the JSON equivalent of xpath.
To find the isInvalid field no matter where it is in the json, you would use it like this:
jsonPath(data, "$..isInvalid")
I want to check the response.data.totalRows is empty.
if (response!=undefined
&& response.data!=undefined
&& response.data.totalRows!=undefined) {
alert(response.data.totalRows);
}
Can simplify the code?
UPDATE: it seems that there is no simple method like isEmpty(response.data.totalRows).
Yea, you can simply do this:
if (response && response.data && response.data.totalRows) {
alert(response.data.totalRows);
}
In JavaScript, a object is cast to a truthy value, when used in a if. This means you can just "dump" the variable in a if or any other boolean statement, as a check to see whether or not it exists. this blog post has some more information about it.
Please note that this will not alert anything if totalRows equals 0 (since 0 is considered a falsy value.) If you also want to alert if it's 0, use this:
if (response && response.data &&
(response.data.totalRows || response.data.totalRows === 0)) {
alert(response.data.totalRows);
}
Or:
if (response && response.data && response.data.totalRows !== undefined) {
alert(response.data.totalRows);
}
Supposing that response.data.totalRows must be an array you can use just:
if (!response.data.totalRows.length) {
/* empty array */
}
If you are not sure that totalRows exists you must verify:
if (
!response ||
!response.data ||
!response.data.totalRows ||
!response.data.totalRows.length
) {
/* is empty */
}
Any value is converted in Boolean. For example: Boolean(response) will return false if response will be 0, null, undefined etc.
What about a try-catch block?
try{ alert(response.data.totalRows); }
catch(e) { alert("undefined"); }
I'd write a prototype (even if it's not recommended)
Object.prototype.isEmpty = function(){
return (!this || this===undefined || this===null || !this.hasChildNodes())
?true
:false;
}
And then just use
if(!response.isEmpty()) alert(response.data.totalRows);
It is only handy if you need the checks also elsewhere and not only one place.
Just
response && response.data && response.data.totalRows && alert(response.data.totalRows)
If the property list gets very long there is another syntax you can use, in the sample code I've created a function so it can be re used.
// args is { object: the object to check the properties of
// properties: an array of strings with property names}
function isSet(args){
//no checking of arguments
var o = args.object,
props = args.properties,
i = -1,len = props.length
while(typeof o !== "undefined"
&& o !== null
&& ++i<len){
o = o[props[i]];
}
return (typeof o !== "undefined"
&& o !== null)?true:false;
}
var test = {
prop1 : {
prop2 : "ok"
}
};
//check if test.prop1.prop2 is set
console.log(isSet({
object:test,
properties: ["prop1","prop2"]
}));//=true
Possible Duplicate:
Detecting an undefined object property in JavaScript
javascript undefined compare
How we can add a check for an undefined variable, like:
function A(val) {
if (val == undefined)
// do this
else
// do this
}
JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.
However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform:
if (typeof value === "undefined") {
// ...
}
It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.
In this case you can use a === undefined comparison: if(val === undefined)
This works because val always exists (it's a function argument).
If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you'd have to use if(typeof val === 'undefined') to avoid an exception in case val didn't exist.
Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.
function A(val){
if(typeof(val) === "undefined")
//do this
else
//do this
}
I know I am late to answer the function but jquery have a in build function to do this
if(jQuery.type(val) === "undefined"){
//Some code goes here
}
Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.
You can use shorthand technique to check whether it is undefined or null
function A(val)
{
if(val || "")
//do this
else
//do this
}
hope this will help you
when I am testing "typeof obj === undefined", the alert(typeof obj) returning object, even though obj is undefined.
Since obj is type of Object its returning Object, not undefined.
So after hours of testing I opted below technique.
if(document.getElementById(obj) !== null){
//do...
}else{
//do...
}
I am not sure why the first technique didn't work.But I get done my work using this.
If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0:
var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr'];
jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) {
var $_oField = jQuery("input[name='"+sShowKey+"']");
if($_oField.val().trim().length === 0){
$_oField.val('0.0')
}
})
I am not sure it is the best solution, but it works fine:
if($someObject['length']!=0){
//do someting
}
function isValue(value, def, is_return) {
if ( $.type(value) == 'null'
|| $.type(value) == 'undefined'
|| $.trim(value) == ''
|| ($.type(value) == 'number' && !$.isNumeric(value))
|| ($.type(value) == 'array' && value.length == 0)
|| ($.type(value) == 'object' && $.isEmptyObject(value)) ) {
return ($.type(def) != 'undefined') ? def : false;
} else {
return ($.type(is_return) == 'boolean' && is_return === true ? value : true);
}
}
try this~ all type checker
Check if undefined or not
if(typeof myVal === "undefined") {
//some code
}
Check if undefined or null or empty or false or 0
if(!myVal) {
// some code
} else {
// myVal is flawless
}