Understanding JavaScript Equality and the Need for TypeScript

Understanding JavaScript Equality and the Need for TypeScript

Bizarre Behaviors in JavaScript - lesson 3

In this article, I intend to examine the equality operator. Why does this topic require investigation? Because we've become accustomed to the characteristics of JavaScript. This tutorial will prevent surprises when working with TypeScript.

In JavaScript, we must be mindful of when to use == and ===. In the case of the double equals (==), JavaScript is not strict. For example, when comparing a string with a number, JavaScript first converts the string to a number and then performs the comparison. Here are two JavaScript examples:

5 == "5"; // JavaScript: true
5 === "5"; // JavaScript: false

In the first case, JavaScript did not enforce strict equality. It performed type conversion and then carried out the comparison. However, in TypeScript, we are not allowed to do this, and we will receive an error.

Let's examine some other peculiar behaviors of JavaScript (these examples are for JavaScript):

console.log("" == "0"); // false
console.log(0 == ""); // true

console.log("" === "0"); // false
console.log(0 === ""); // false

In the first line, both values are strings. Therefore, we are comparing strings, and it is clear that "0" is not equal to an empty string "", so the output is false.

An interesting point is in the second line where both 0 and "" are treated as false in JavaScript. Try typing false == 0 in the browser console and see the result.

When we use ===, the output of these two comparisons is false (as it should be).

Note: != and !== exhibit the same behavior as == and ===.

Structural Comparison

When we compare the entire structure of two objects, == and === are not suitable. See the following code:

console.log({ a: 5 } == { a: 5 }); // false
console.log({ a: 5 } === { a: 5 }); // false

In the above code, even though the two objects appear to be the same, both == and === yield false. What should we do to get true? We can use the deep-equal package as follows:

import * as deepEqual from "deep-equal";

console.log(deepEqual({ a: 5}, { a: 5 })); // true

That's it for today's session. In future sessions, we will become more familiar with TypeScript and its commands. Please feel free to ask your questions and share your comments in the comments section.