There are multiple ways of doing this, and certain things might not even work.


if (a) {

This will check for null, undefined, NaN, empty string (""), 0, false.

Now the long answer.

typeof : This works for undefined variables and it returns a string. Also this does not work with null variables. Also it is believed to be faster than just the undefined comparison.

let a;
console.log(typeof a);
// "undefined"

let b = null;
console.log(typeof b);
// "object" 

So what to do for null variables? Well you that you can just compare it with null.

let a = null;

console.log(a === null);
// true

/* Also note */
let d;

console.log(d == null);
// true

console.log(d === null);
// false

undefined == null but undefined !== null

Also, never go with the null comparison only else it will throw undefined errors if you check on an undefined or out of scope variable.

console(d == null);
// Throws ReferenceError

/* Maybe use both undefined and null check */

console.log(typeof d !== "undefined" && d !== null);
// false

Maybe add a length check as well to handle empty strings and arrays if you are looking for that.

	typeof d !== "undefined" && d !== null && d.length !== 0
// false

Or you could be a sane person and just use the if check that was mentioned first.

if (a) {
	// A sane person's block