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
}
This question already has answers here:
Javascript test ( object && object !== "null" && object !== "undefined" )
(11 answers)
Closed 3 years ago.
I have this piece of code where I check if hostel.country.address is null but nevertheless
return hostel.country.address &&
hostel.country.address.internalEmployeeIdentifier !== null ||
hostel.country.address.externalEmployeeIdentifier !== null;
I have this compilation problem on
hostel.country.address
Object is possibly 'null' or 'undefined'.
- error TS2533: Object is possibly 'null' or 'undefined'.
return hostel.country.address &&
hostel.country.address!.internalEmployeeIdentifier !== null ||
hostel.country.address!.externalEmployeeIdentifier !== null;
should work.
Good luck
Please try this
const address = hostel?.country?.address
return address?.internalEmployeeIdentifier !== null || address?.externalEmployeeIdentifier !== null
You can use optional chaining (you should install the babel plug in)
and then your code will be something like:
hostel?.country?.address
more information can be found at:
https://github.com/tc39/proposal-optional-chaining
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
installation:
https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining#installation
settings .babelrc
{
"plugins": ["#babel/plugin-proposal-optional-chaining"]
}
Add something like this, then modify your return line to use it:
function isValid(test) {
return !(test === null || test === undefined);
}
Your return could look like:
return isValid(hostel) &&
isValid(hostel.country) &&
isValid(hostel.country.address) &&
(isValid(hostel.country.address.internalEmployeeIdentifier) ||
isValid(hostel.country.address.externalEmployeeIdentifier));
When you have nested properties and parent property may or may not exist, it is good to take help of some external library. something like this can make it much simpler
const _ = require('lodash');
if(_.get(hostel, 'country.address.externalEmployeeIdentifier')) {
// do something
}
this way you do not need multiple && conditions. The library will take care of it.
One more way is to use object destructuring with default values.
const {
country: {
address: { internalEmployeeIdentifier, externalEmployeeIdentifier } = {}
} = {}
} = hostel || {};
return (
internalEmployeeIdentifier !== null || externalEmployeeIdentifier !== null
);
My code is getting really quite polluted with:
if( typeof( objectVar ) === 'object' && objectVar !== 'null' )
if( typeof( objectVar.other ) === 'object' && objectVar.other !== 'null' )
// OK, objectVar.other is an object, yay!
}
}
This is a little ridiculous. I am after a function that reads like this:
isProperObject( objectVar.other );
Considering that if objectVar is not defined, this will actually fail miserably, maybe I should do instead:
isProperObject( 'objectVar.other' );
Then the function could eval() it. But no! It cannot do that, because isProperObject() would be in a different scope, one without objectVar.
So, it could be:
isProperObject( objectVar, 'other' )
OK this could work. Is there a function like this that is actually commonly used?
Your checks are needlessly verbose. You can do this instead:
if (objectVar != null && objectVar.other != null) {
// OK, objectVar.other is an object, yay!
}
This will check for both null and undefined, and so gives you the safety you need.
Or if you really need .other to be an object:
if (objectVar && typeof objectVar.other === "object") {
// OK, objectVar.other is an object, yay!
}
Also, you should have been testing for:
!== null
instead of:
!== 'null'
A different, novel approach is this:
if((objectVar || {}).other != null) {
Move to a "higher level" of programming and initialize values to a null or empty object.
You should be working with top- and intermediate-level objects which are initialized to usable values, and you thus know to exist. Only the "leaf" objects should potentially be in empty/ null state.
For example, instead of:
var dialogTitle;
var dialogId;
var dialogElement;
Prefer to build a valid container object, in an "empty" state.
var dialog = {
title: null,
id: null,
element: null
};
You can also use if (dialog.id != null) or, when you're not expecting false or 0 values, if (dialog.id).
I was wondering if there is an alternative to the classic.
if (typeof firstPost === 'object' && typeof firstPost.active === 'boolean' && typeof firstPost.message === 'string' && typeof firstPost.maxHeight)
So as to avoid writing more code, maybe looping object.
I would use this:
if this is user input
var firstPost = {
active : true,
message : "hello",
maxHeight : 20
}
then:
var checks = {
active : 'boolean',
message : 'string',
maxHeight : 'number'
}
try {
for(var key in checks) {
if(typeof firstPost[key] != checks[key]) {
throw new Error(key + " is not " + checks[key]);
}
}
}catch(e) {
alert(e.toString());
}
this is not bytesless, but it's more clean. (and it checks also if all keys are defined)
EDIT:
There is no way more compact. However you can declare some function in another place and call it.
function checkObject(obj,checks) {
for(var key in checks) {
if(typeof obj[key] != checks[key]) {
return false;
}
}
return true;
}
and simply
checkObject(firstPost,{
active : 'boolean',
message : 'string',
maxHeight : 'number'
});
You can elaborate another return type in order to specify the error.
If there are always the same types and you're needing this exact if more often, you could wrap it in a function.
Otherwise your if construct is the only real possibility you have I think. Of course you could create an object with the key as fieldname and the value as the required type, but I wouldn't do that, as it won't be easiliy readable anymore.
only thing that comes to my mind that would shorten this code (a little bit), is wrapping the typeof function into something like this:
function is(variable, type){
return typeof variable == type;
}
So you could just call it like is(firstPost, 'object') and so on
Looping object or using another way will have more code than you wrote.
Of course you can use "||" method to compare in javascript or kind of "? :" if else statement.
The first check can be simplified, because object instances are truthy !!{} === true, and you don't need to check specifically for object because you are checking if it has the properties later.
And most times you only need to know if there is data inside the object and not exactly if it is of a specific type:
function notUndef (aux) {
return aux !== undefined;
}
if (firstPost && notUndef(firstPost.active) && notUdenf(firstPost.message) && notUndef(firstPost.maxHeight))
If you have a really long list of properties to check you can use a loop:
function checkHasProps (obj, properties) {
obj || return false;
var hasAll = true;
properties.forEach(function (prop) {
if (obj[prop] === undefined) {
hasAll = false;
}
});
return hasAll;
}
if (checkHasProps(['active', 'message', 'maxHeight', (...)]));
And remember that typeof [] === 'object', so typeof is not a completly reliable way to check things.
There are a variety of places where I need to check if a JavaScript variable is null or empty string so I wrote an extension method that looks like this:
Object.prototype.IsNullOrEmptyString = function()
{
return (this == null || (typeof this === "string" && this.length == 0));
}
I then call it like so:
var someVariable = null;
if (someVariable.IsNullOrEmptyString())
alert("do something");
But that doesn't work because, at the point of evaluation in the if statement, someVariable is null. The error I keep getting is "someVariable is null".
You can see it live here: http://jsfiddle.net/AhnkF/ (run in Firefox and notice the error console)
Is there anyway to do what I want and have a single extension method check for null and other things at the same time?
null does not have any properties or methods. You have to create a function, and pass the variable, so it can be tested. Note: To test whether a variable is really an empty string, using === "" is recommended.*
function isNullOrEmpty(test) {
return test === null || test === "";
}
var someVariable = null;
if (isNullOrEmpty(someVariable)) alert("Do something");
* about == and ===. The following comparisons are true:
null == undefined
"" == 0;
"" == false
"" ==
Because your variable is not an object, so its not working. Do it this way.
Object.prototype.IsNullOrEmptyString = function(obj)
{
return (obj == null || (typeof this === "string" && this.length == 0));
}
if(Object.IsNullOrEmptyString(null))
alert('yes');
just make it a function call.
function IsEmptyString(value)
{
return (value == null ||
value === "");
}
Here is a fiddle
Edit: consolidated (=== undefined and === null) into (== null)