Every JavaScript beginner gets confused when checking JavaScript variable, value is defined or not if defined then value is blank or has a value. So I am going to explain this.
undefined: it means a variable has declared but has not assigned a value, let me explain with an examples
var name; console.log(name); //output will be undefined console.log(typeof name); //output will be undefined
So JavaScript variable undefined condition should be
if( typeof name !== 'undefined' ) { // your code }
null: it means variable is assigned with null which means a variable has no value, let’s see the example for better understanding
var name =null; considers.log(name); //output will be null console.log(typeof name) //output will be object
if you want to check whether the value is assigned or not always check with this condition
if( typeof value == 'undefined' || variable == null ){ // your code }
now lets check variable has a string or number value assigned
var x = 'Abhay' var y = 1;
console.log(typeof x); //output will be a string so for string checking condition will be if( typeof value === 'string'){
// your code
} console.log( typeof y);
//output will be number so for number checking condition will be if( typeof value === 'number'){
// your code
}
I hope this will be helpful to JavaScript variable assignment checking.
You may like: JavaScript Tips & Tricks
Originally published at https://codinghub.net.