Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/jquery/how-to-check-empty-null-and-undefined-variables-in-javascript-jquery
Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!
In this post, I will share a basic code in Javascript/jQuery that checks the empty, null, and undefined variables. If you using javascript/jquery usually you need to check if the variable given is not empty, nulled, or undefined before using it to your function. Because if you don't validate your variables it could cause an error to your javascript code.
Check empty variable
In this example, I have an if statement in javascript that will check the variable is empty.
var a = '';
if(a == ''){
console.log('Empty');
}
Check null variable
In this example, it will check the nulled variable before executing it.
var a = 'codeanddeploy';
if(a == null || a == NULL){
console.log('Nulled');
}
Check undefined variable
As you can see below, I used typeof() function in javascript to determine variable data type.
if(typeof a == "undefined"){
console.log('undefined');
}
I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/jquery/how-to-check-empty-null-and-undefined-variables-in-javascript-jquery if you want to download this code.
Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!
Happy coding :)
Top comments (4)
Going off the top of my head, but I might be missing a few idiosyncracies of JS (like operand order, lol)
== ''
does not work for, e.g.[]
, but will work forfalse
and""
.NULL
doesn't exist, but may at best be an alias fornull
, making that a redundant or broken condition.typeof undefined
over"undefined"
.Your 'check null variable' code does not work - will cause an error. It also demonstrates a lack of knowledge of JS
The first check is for an empty string. I am not aware of something like "NULL". Also let me add, that for checking for undefined or null you can just write the variable without anything else in the brackets of the condition, like "if (variable) ...". Please correct wrong points in case these are given and also have a look at the linked articles, which can have the same issues.
You're also checking to see if the variable is equal to the string value "undefined". I'm sorry, but this is a very poor post and should be avoided.