When it comes to comparisons, Javascript has a few quirks that are often difficult to remember. Instead of trying to keep it in my head, here's a little cheatsheet I use to keep things in check.

Quirks

So there's one quirk that you must know about in Javascript. undefined is mutable. Therefore you can assign a value to undefined. This isn't good and one of the reasons why you must compare objects differently.

Objects

Test for null

Test whether a variable is null. The === will prevent mistakes and keep you from losing your mind.

var myVar;
var isNull = (myVar === null);

Test for undefined

Unlike null, you cannot do this. It will work against you because in Javascript, undefined is mutable, and therefore you can assign something to it.

// BAD BAD BAD BAD BAD BAD BAD BAD BAD
var isUndefined = (myVar === undefined); 
// BAD BAD BAD BAD BAD BAD BAD BAD BAD

This is the correct way to test for undefined.

var isUndefined = (typeof myVar === 'undefined');

Test for empty

If you prefer not to use a library like lodash, here are two ways to check if an object is empty.

Method 1 - Simple Function

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

var myObj = {}; 
// If Object is Empty
if(isEmpty(myObj)) {
    console.log("empty");
} 
// Object is not Empty
else {
    console.log("not empty");
}

Method 2 - Extending Object Class

Object.prototype.isEmpty = function() {
    for(var key in this) {
        if(this.hasOwnProperty(key))
            return false;
    }
    return true;
}

var myObj = new Object()
myObj['a'] = 1;
myObj.isEmpty(); //False

Test if two objects are the same

These two objects are the same.

var myObj = { a: 1 };
Object.is(myObj, myObj); //True

These two objects are not the same.

var myObj = { a: 1 };
var myObj2 = { a: 1 };
Object.is(myObj, myObj2); //False

Arrays

This checks to see if array is undefined, null, or empty.

let myArray = [];
// Array does not exist, is not an array, is empty
if (!Array.isArray(myArray) || !array.length) {

}
  1. Array.isArray() checks whether its argument is an array. This weeds out values like null, undefined, and anything else that is not an array.
  2. array.length determines if there are objects in the array.

Source


Resources