Operators & Type Coercion

How JavaScript compares, computes, and quietly converts values behind the scenes when types don't match.

JavaScript7 min readConcept 4 of 62

What are operators and coercion?

Operators are symbols used to perform operations on operands. JavaScript includes arithmetic (+, -, *, /), logical (&&, ||, !), and comparison operators (==, ===, >, <).

Type coercion is JavaScript's automatic or implicit conversion of values from one data type to another (such as strings to numbers) when performing an operation.

Why does it matter?

JavaScript is a dynamically typed language, which means it tries to be helpful by converting types automatically to make an operation succeed.

While this seems convenient, implicit coercion is the source of many notoriously confusing bugs. Understanding how values convert is essential to writing predictable code.

Strict vs Loose Equality

The loose equality operator (==) compares two values after attempting to convert them to a common type. For example, 5 == '5' is true because the string is coerced to a number.

The strict equality operator (===) compares both the value and the type without doing any coercion. 5 === '5' is false.

Always use === unless you have a specific reason to use loose equality.

Coercion Comparator

Compare different values using both loose (==) and strict (===) equality. See how JavaScript coerces the types before comparing them loosely.

Equality Comparator

console.log(
5=="5"
);
Console OutputCoercion triggered
true

JavaScript converts the string to a number before comparing.

iLoose equality (==) tries to coerce values to the same type before comparing. This causes notorious bugs.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the result of `"5" + 3`?
  2. 2What is the result of `"5" - 3`?
  3. 3Which of these values is NOT falsy?

Remember this

  • Always use strict equality (===) instead of loose equality (==) to avoid unexpected coercion.
  • The 6 falsy values are: false, 0, "", null, undefined, NaN.
  • The + operator coerces to string if any operand is a string. Other math operators (-, *, /) coerce to numbers.

Done with this concept?

Mark it complete to track your progress. No login needed.