Reading history

JavaScript Type Conversion, Truthy/Falsy and == vs ===

6 min read 1 views

Learn JavaScript type conversion: Number, parseInt and String, how + joins strings, falsy values, NaN checks, and why === beats == for comparisons.

JavaScript is relaxed about types. Ask it to subtract a string from a number and it quietly turns the string into a number; ask it to add them and it turns the number into a string instead. This automatic type conversion (also called coercion) explains strange results such as "5" + 3 giving "53", and it is the reason JavaScript has two equality operators. This lesson shows how conversion works, which values count as true or false, and why you should almost always use ===.

In this lesson you will learn

  • Converting explicitly with Number, parseInt, String and Boolean
  • How implicit conversion works with + and other operators
  • The falsy values and everything that is truthy
  • Why NaN is never equal to itself
  • The difference between ==, === and Object.is

You should know data types and operators.

Explicit and Implicit Conversion

"use strict";
// Explicit conversion: say what you want
console.log(Number("42"), Number("  7  "), Number(""), Number("12px"), Number(true), Number(null), Number(undefined));
console.log(parseInt("12px"), parseFloat("3.75 kg"), parseInt("0x1F"), parseInt("101", 2));
console.log(String(99), (255).toString(16), String(null), String([1, 2]));
console.log(Boolean(0), Boolean(""), Boolean("0"), Boolean([]), Boolean({}));

// Implicit conversion: JavaScript guesses
console.log("5" + 3, "5" - 3, "5" * "2", "10" / 4, true + 1, [] + [], "3" + 4 + 5, 3 + 4 + "5");

// The six falsy values (plus 0n); everything else is truthy
const values = [0, -0, "", null, undefined, NaN, "false", " ", [], {}];
console.log(values.map(v => (v ? "T" : "F")).join(" "));

// NaN is not equal to anything, even itself
const x = Number("abc");
console.log(x === NaN, Number.isNaN(x), isNaN("abc"), Number.isNaN("abc"));

Output

42 7 0 NaN 1 0 NaN
12 3.75 31 5
99 ff null 1,2
false false true true true
53 2 10 2.5 2  345 75
F F F F F F T T T T
false true true false
  • Number() converts a whole value: spaces around a number are ignored, an empty string becomes 0, and anything else that is not a number becomes NaN (“not a number”).
  • parseInt and parseFloat read digits from the start and stop at the first character they do not understand, so "12px" gives 12. The second argument of parseInt is the base: parseInt("101", 2) reads binary.
  • String() and .toString() convert to text; (255).toString(16) gives hexadecimal.
  • With +, if either side is a string, the other side is converted to a string and the two are joined: "5" + 3 is "53". The other arithmetic operators convert to numbers: "5" - 3 is 2. [] + [] gives an empty string, shown as the extra gap in the output.
  • Expressions run left to right: "3" + 4 + 5 is "345", but 3 + 4 + "5" adds first and gives "75".
  • Only a few values are falsy: 0, -0, "", null, undefined, NaN (and 0n). Everything else is truthy, including "false", a space, an empty array and an empty object.
  • NaN === NaN is false. Test with Number.isNaN(). The older global isNaN() converts its argument first, so it returns true for any non-numeric string.

== vs === vs Object.is

"use strict";
// == converts types before comparing; === does not
const pairs = [
  [0, "0"], [0, ""], ["", "0"], [null, undefined], [null, 0],
  [false, "0"], [1, true], [NaN, NaN], [[1], 1],
];
console.log("a".padEnd(12), "b".padEnd(12), "==", "  ===");
for (const [a, b] of pairs) {
  const show = v => (typeof v === "string" ? `"${v}"` : Array.isArray(v) ? `[${v}]` : String(v));
  console.log(show(a).padEnd(12), show(b).padEnd(12), String(a == b).padEnd(5), a === b);
}

// Object.is is like === but handles NaN and -0 correctly
console.log(Object.is(NaN, NaN), Object.is(0, -0), 0 === -0);

// Objects are compared by reference, not by content
const p = { x: 1 }, q = { x: 1 }, r = p;
console.log(p === q, p === r, JSON.stringify(p) === JSON.stringify(q));

// Safe user-input check: convert first, then compare strictly
const input = "18";
const age = Number(input);
console.log(Number.isInteger(age) && age >= 18 ? "adult" : "not adult");

Output

a            b            ==   ===
0            "0"          true  false
0            ""           true  false
""           "0"          false false
null         undefined    true  false
null         0            false false
false        "0"          true  false
1            true         true  false
NaN          NaN          false false
[1]          1            true  false
true false true
false true true
adult
  • === (strict equality) is true only when both the type and the value match. Every pair in the table except NaN and NaN has different types, so === is false; NaN is never equal to anything.
  • == (loose equality) converts types first, with rules that are hard to remember: 0 == "" and 0 == "0" are true, yet "" == "0" is false. That breaks the normal logic that if a equals b and a equals c, then b equals c.
  • The one widely used == case is value == null, which is true for both null and undefined and nothing else. Many teams still prefer writing value === null || value === undefined, or using ??.
  • Object.is is like === except that it treats NaN as equal to itself and tells 0 and -0 apart.
  • Objects and arrays are compared by reference: two objects with the same content are still different objects. Only a variable pointing at the same object is equal.
  • For user input, convert explicitly with Number(), check the result, and then compare strictly.

Conversion Cheat Sheet

ValueNumber(value)String(value)Boolean(value)
""0""false
"42"42"42"true
"abc"NaN"abc"true
null0"null"false
undefinedNaN"undefined"false
true1"true"true
[]0""true
[5]5"5"true

Common Mistakes

  1. Adding numbers read from inputs: input.value is always a string, so a.value + b.value joins text. Convert with Number() first.
  2. Checking if (count) when 0 is a valid value; 0 is falsy. Compare explicitly, or use ?? for defaults.
  3. Testing for NaN with ===.
  4. Comparing arrays with === to check if they hold the same items.

Practice Exercises

Exercise 1. Predict the results: "10" * "2", "10" + 2 - 1, true + true.

Show answer

20 (both converted to numbers), 101 ("102" - 1), and 2 (each true becomes 1).

Exercise 2. Write toNumberOrNull(text) that returns a number for valid numeric text and null otherwise, treating an empty string as invalid.

Show answer
function toNumberOrNull(text) {
  if (text.trim() === "") return null;
  const n = Number(text);
  return Number.isFinite(n) ? n : null;
}

Frequently Asked Questions

Should I ever use == in JavaScript?

Most style guides say to use === everywhere. The only common exception is x == null to catch both null and undefined, and even that is a matter of team preference.

What is the difference between Number() and parseInt()?

Number() requires the whole string to be a number and returns NaN otherwise; it also handles decimals. parseInt() reads whole-number digits from the start and ignores the rest, which suits values like "20px" but can hide mistakes.

Summary

  • + with a string joins text; other operators convert to numbers.
  • Learn the falsy values; everything else is truthy.
  • Use Number.isNaN, not === NaN.
  • Use ===; == applies confusing conversions.

Next: Sorting, Searching and Grouping Arrays.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *