Home » Programming » Javascript » Checking for Equality (And Inequality) in JavaScript, with Examples

Checking for Equality (And Inequality) in JavaScript, with Examples

This article will explain equality and inequality in the JavaScript Programming language, and provide code examples showing how to check if values are equal in value and type.

Checking whether two values are equal can get a bit confusing in JavaScript – there is loose equality and strict equality involving types to consider. Read on to find out how testing for equality and inequality works in JavaScript.

What are equality and inequality?

In programming, equality is the process of checking whether two values are equal (or not equal). The result of this check is usually then used to make a decision, creating the logic that directs the flow of your application.

For example, you may check whether the amount a customer has tended during a cash transaction is equal to the sale total – if the amounts are equal, no money is owed and transaction ends – if not, either the customer will to proffer more money or the shop will issue change.

Equality is not just limited to numerical values. If, for example, you were searching through an array of employee records, you could check wether an employees name was equal to another to remove duplicates, or whether it is equal to a searched name for looking up records.

Checking for Equal Values

Any type of primitive value can be checked for equality – strings, numbers, and boolean values. Objects however cannot be checked for equality without a bit of extra work – We’ll cover that later.

For all of the methods outlined below, the expected result of each comparison will be a boolean TRUE or FALSE value.

Don’t Use the Equal Operator (=)!!

One common mistake when comparing values in JavaScript is to use the = (equals) operator when doing so. This will not work as = is reserved for variable assignment.

Checking for Equal Value (==)

The == (equality) operator compares two values. If the values are of different types (eg you are comparing a number and a string), it will try to convert the values to the same type for comparison. Here are some examples:

3.14 == "3.14"; // Returns TRUE - The string will be coerced into a number (or the reverse) before the values are compared
3.14 == 3.14; // Returns TRUE - both values are the same
3.14 == 4; // Returns FALSE - the values are not the same
3.14 == true; Returns FALSE - boolean values can only be coerced to a value of 0 or 1

Comparison is not usually done directly between values, but between a value and a variable, or two variables:

var pi = 3.14;
var eulers = 2.71;

pi == eulers; // FALSE 
pi == 3.14 // TRUE 

Checking for Not-Equal Values (!=)

The value of any equality check can be inverted by instead using != – the inequality operator:

3.14 != 3.14; // Returns FALSE - both values are equal, and we are checking for inequality

Strict Full Equality of both Value and Type

The == operator tries to convert values to the same type before comparison, but you may not want to do this. For strict equality checks, use the === operator to prevent types from being coerced before comparison. Only values of both the same value and type will be considered equal:

3.14 === "3.14"; // Returns FALSE - Numbers and strings are different types of variable
3.14 === 3.14; // Returns TRUE - both values are the same, and both are numbers

Strict inequality

Similarly, strict inequality can be used using the !== (strict inequality) operator, ensuring that values of different types are always considered unequal:

3.14 !== "3.14";

Checking and Comparing Types with typeOf

If you need to check whether two values are of the same type, you can use the typeof operator:

typeof "3.14" == typeof 3.14;

The above will return FALSE as the first value is a string, while the second is a number.

Floating Number Comparisons/Problems Comparing Calculated Values

Floating point numbers can cause problems when comparing calculated values as they are imprecise. If you wind up with a floating point error, an equality check may fail even if the values are expected to be equal.

There is no magic bullet for this. You will need to decide on the preciseness required for your comparison and then use the toFixed() method to convert your calculated values to an appropriate fixed number of decimal places before comparing them.

(0.1 + 0.7) == 0.8 // Will return FALSE (though it should be true!) due to floating point error
(0.1 + 0.7).toFixed(1) == 0.8  // Will return TRUE as the first value has been rounded to a single decimal place to account for the forseen floating point error

Object equality

Objects will not pass checks using the equality operators above unless they are both references to the same variable.

// Create an object representing an apple
var apple = {
    name: "apple",
    colour: "green"
};

// Create a new variable that is a reference to the existing variable
var appleRef = apple;

// Test the equality of the original variable and the reference
apple == appleRef; // TRUE because they are references to the same variable

// Create a separate, but identical apple object
secondApple = {
    name: "apple",
    colour: "green"
};

// Compare the two identical objects
apple == secondApple; // FALSE as objects fail equality checks

To properly compare objects, you can employ the following trick:

JSON.stringify(apple) == JSON.stringify(secondApple); // TRUE - By converting the objects to JSON strings, they can be compared.

The above method does require that the objects attributes are in the same order, and does not consider the object class or any methods that may be present, but is a good way to determine equality for most situations.

If you are looking to a deep comparison of two objects, it’s probably simplest to use lodash’s isEqual method.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment