JavaScript Truthy and Falsy Values, == vs === and Object.is
Every if statement, every loop condition and every assertion depends on two questions: “is this value true enough?” and “are these two values equal?”. JavaScript answers both with rules that surprise people coming from other languages: an empty array is true, "0" == 0 is true, and { id: 1 } is not equal to { id: 1 }. In this lesson you will learn those rules, the safe habits that avoid the traps, and how to compare objects and arrays properly in tests.
📖 What You’ll Learn: the eight falsy values, truthy values that surprise people, Boolean() and the double NOT (!!), how conditions use truthiness, loose equality == and its coercion rules, strict equality ===, Object.is, comparing objects and arrays by reference and deeply, comparing strings, and common equality bugs in tests.
🌗 Truthy and Falsy Values
Definition: wherever JavaScript expects a boolean (in if, while, &&, ||, ! and the ? : operator), it converts the value to true or false. Values that become false are falsy; every other value is truthy.
There are exactly eight falsy values:
| Falsy value | Type |
|---|---|
false | boolean |
0 and -0 | number |
0n | bigint |
"" (empty string) | string |
null | null |
undefined | undefined |
NaN | number |
Everything else is truthy, including several values that look “empty”:
📄 truthy.js
const surprises = [
["\"0\"", "0"], ["\"false\"", "false"], ["\" \"", " "], ["[]", []],
["{}", {}], ["-1", -1], ["Infinity", Infinity], ["new Date(0)", new Date(0)],
];
for (const [label, value] of surprises) {
console.log(`${label.padEnd(12)} is ${value ? "truthy" : "falsy"}`);
}
⌨️ Terminal
node truthy.js
🖥️ Output
"0" is truthy
"false" is truthy
" " is truthy
[] is truthy
{} is truthy
-1 is truthy
Infinity is truthy
new Date(0) is truthy
⚠️ Watch out: An empty array [] and an empty object {} are truthy. To check for “no items”, test the length: if (results.length === 0), or Object.keys(obj).length === 0 for objects.
🔁 Boolean() and the Double NOT (!!)
To get the actual boolean, use Boolean(value) or !!value. The first ! converts and negates, the second negates back.
📄 boolean.js
const username = "asha";
const token = "";
const retries = 0;
console.log(Boolean(username), !!username);
console.log(Boolean(token), !!token);
console.log(!retries); // single ! : "is retries falsy?"
const hasItems = !![1, 2].length;
console.log({ hasItems });
⌨️ Terminal
node boolean.js
🖥️ Output
true true
false false
true
{ hasItems: true }
🚦 Truthiness in Conditions (and the 0 Trap)
Short checks such as if (name) are idiomatic JavaScript, and they read well:
📄 condition.js
function greet(name) {
if (name) {
return `Hello, ${name}!`;
}
return "Hello, guest!";
}
console.log(greet("Asha"));
console.log(greet(""));
console.log(greet(undefined));
⌨️ Terminal
node condition.js
🖥️ Output
Hello, Asha!
Hello, guest!
Hello, guest!
But truthiness treats a real value of 0 or "" as “missing”. This bug appears constantly with quantities, prices and scores:
📄 zero-trap.js
function describeStock(qty) {
if (!qty) return "stock unknown"; // bug: 0 is a real stock level
return `${qty} in stock`;
}
console.log(describeStock(5), "|", describeStock(0), "|", describeStock(undefined));
function describeStockFixed(qty) {
if (qty === undefined || qty === null) return "stock unknown";
return `${qty} in stock`;
}
console.log(describeStockFixed(5), "|", describeStockFixed(0), "|", describeStockFixed(undefined));
⌨️ Terminal
node zero-trap.js
🖥️ Output
5 in stock | stock unknown | stock unknown
5 in stock | 0 in stock | stock unknown
💡 Tip: Use a truthiness check when “empty” and “missing” mean the same thing (an empty search term). Use an explicit comparison when 0, "" or false are valid values. The next lesson shows ??, which was designed for exactly this.
⚖️ Loose Equality (==) vs Strict Equality (===)
Definition: strict equality === returns true only when both values have the same type and the same value. Loose equality == first converts the values to a common type (coercion) and then compares. !== and != are their opposites.
📄 equality.js
console.log("1" == 1, "1" === 1);
console.log(0 == "", 0 === "");
console.log(0 == false, 0 === false);
console.log("" == false, "" === false);
console.log(null == undefined, null === undefined);
console.log(null == 0, null >= 0); // a famous inconsistency
console.log(NaN == NaN, NaN === NaN);
console.log([1] == 1, [1, 2] == "1,2");
⌨️ Terminal
node equality.js
🖥️ Output
true false
true false
true false
true false
true false
false true
false false
true true
The loose rules, simplified:
- If the types are the same, compare like
===. nullandundefinedare equal to each other and to nothing else.- Otherwise, booleans become numbers, strings become numbers when compared with numbers, and objects are converted to primitives.
| Comparison | == | === |
|---|---|---|
"5" vs 5 | true | false |
0 vs "" | true | false |
0 vs false | true | false |
null vs undefined | true | false |
null vs 0 | false | false |
NaN vs NaN | false | false |
💡 Tip: Always use === and !==. The single accepted exception is value == null, a short way to test for null or undefined. ESLint’s eqeqeq rule enforces this.
🔍 Object.is: The Strictest Comparison
Object.is(a, b) is like === with two differences: it treats NaN as equal to NaN, and it distinguishes 0 from -0.
📄 object-is.js
console.log(NaN === NaN, Object.is(NaN, NaN));
console.log(0 === -0, Object.is(0, -0));
console.log(Object.is("qa", "qa"), Object.is({}, {}));
⌨️ Terminal
node object-is.js
🖥️ Output
false true
true false
true false
You rarely need it in everyday code, but testing frameworks use it: Jest’s and Playwright’s toBe() compare with Object.is.
📦 Comparing Objects and Arrays
Objects and arrays are compared by reference: === is true only if both sides are the very same object, even when the contents are identical.
📄 objects-equal.js
const expected = { id: 1, tags: ["smoke"] };
const actual = { id: 1, tags: ["smoke"] };
console.log(expected === actual); // different objects
console.log(expected == actual); // also false
console.log(JSON.stringify(expected) === JSON.stringify(actual)); // quick content check
⌨️ Terminal
node objects-equal.js
🖥️ Output
false
false
true
Comparing JSON strings is fragile because property order matters ({a:1,b:2} and {b:2,a:1} give different strings). For real tests use a deep equality assertion, which compares the contents recursively:
📄 deep-equal.js
const assert = require("node:assert/strict");
const expected = { id: 1, name: "Asha", tags: ["smoke", "ui"] };
const actual = { name: "Asha", id: 1, tags: ["smoke", "ui"] }; // different key order
assert.deepStrictEqual(actual, expected);
console.log("deep equality passed");
const changed = { ...actual, tags: ["smoke"] };
try {
assert.deepStrictEqual(changed, expected);
} catch (err) {
console.log(err.message.split("\n").slice(0, 1).join(""));
}
⌨️ Terminal
node deep-equal.js
🖥️ Output
deep equality passed
Expected values to be strictly deep-equal:
📌 Note: In Playwright and Jest: expect(a).toBe(b) checks identity (Object.is), while expect(a).toEqual(b) and toStrictEqual(b) check deep equality. Using toBe on two objects with the same content fails, which confuses many beginners.
🔤 Comparing Strings
Strings are compared character by character using their Unicode code values. That means uppercase letters sort before lowercase letters, and numbers stored as strings compare alphabetically:
📄 strings-compare.js
console.log("apple" < "banana"); // true
console.log("Zebra" < "apple"); // true: uppercase codes are smaller
console.log("10" < "9"); // true: compares "1" with "9"
console.log("Asha" === "asha");
console.log("Asha".toLowerCase() === "asha".toLowerCase()); // case-insensitive
console.log("résumé".localeCompare("resume", "en", { sensitivity: "base" }) === 0);
console.log(" ok ".trim() === "ok");
⌨️ Terminal
node strings-compare.js
🖥️ Output
true
true
true
false
true
true
true
💡 Tip: Text from web pages often has extra spaces, line breaks or different case. Normalise both sides (trim(), toLowerCase()) before comparing, or use matchers designed for UI text such as Playwright’s toHaveText, which ignores extra whitespace.
🧪 Tester Scenario: Write a Safe Comparison Helper
This helper compares an expected and an actual value the way a test should: strict for primitives, deep for objects, with a readable result.
📄 check.js
const { isDeepStrictEqual } = require("node:util");
function check(label, actual, expected) {
const ok = typeof expected === "object" && expected !== null
? isDeepStrictEqual(actual, expected)
: Object.is(actual, expected);
console.log(`${ok ? "PASS" : "FAIL"} ${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
return ok;
}
const response = { status: 200, count: "3", items: ["a", "b", "c"], error: null };
check("status", response.status, 200);
check("count", response.count, 3); // string vs number: caught
check("count as number", Number(response.count), 3);
check("items", response.items, ["a", "b", "c"]);
check("error", response.error, null);
⌨️ Terminal
node check.js
🖥️ Output
PASS status: expected 200, got 200
FAIL count: expected 3, got "3"
PASS count as number: expected 3, got 3
PASS items: expected ["a","b","c"], got ["a","b","c"]
PASS error: expected null, got null
The second check fails on purpose: the API sent "3" (a string) where a number was expected. With ==, this defect would have passed unnoticed.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write isEmpty(value) that returns true for null, undefined, "", [] and {}, and false for 0, false, "a" and [1].
Show answer
📄 practice1.js
function isEmpty(value) {
if (value === null || value === undefined) return true;
if (typeof value === "string" || Array.isArray(value)) return value.length === 0;
if (typeof value === "object") return Object.keys(value).length === 0;
return false;
}
for (const v of [null, undefined, "", [], {}, 0, false, "a", [1]]) {
console.log(JSON.stringify(v) ?? "undefined", isEmpty(v));
}🖥️ Output
null true
undefined true
"" true
[] true
{} true
0 false
false false
"a" false
[1] falseQ2. Predict each result, then run the code: "" == 0, "0" == false, [] == false, null == false, undefined == null.
Show answer
📄 practice2.js
console.log("" == 0);
console.log("0" == false);
console.log([] == false);
console.log(null == false);
console.log(undefined == null);🖥️ Output
true
true
true
false
truenull is only loosely equal to undefined, so null == false is false. [] == false converts [] to "" and then to 0.
Q3. Fix the bug: a discount of 0% should print Discount: 0%, but it prints No discount.
function showDiscount(percent) {
return percent ? `Discount: ${percent}%` : "No discount";
}
console.log(showDiscount(0));Show answer
📄 practice3.js
function showDiscount(percent) {
return percent === undefined || percent === null ? "No discount" : `Discount: ${percent}%`;
}
console.log(showDiscount(0));
console.log(showDiscount(undefined));🖥️ Output
Discount: 0%
No discountQ4. Compare the arrays [1, 2, 3] and [1, 2, 3] so the result is true using node:util.
Show answer
📄 practice4.js
const { isDeepStrictEqual } = require("node:util");
console.log([1, 2, 3] === [1, 2, 3]);
console.log(isDeepStrictEqual([1, 2, 3], [1, 2, 3]));🖥️ Output
false
trueQ5. A page shows the heading " Welcome, ASHA \n". Check whether it matches the expected text "Welcome, Asha", ignoring case and extra whitespace.
Show answer
📄 practice5.js
const actual = " Welcome, ASHA \n";
const expected = "Welcome, Asha";
const normalise = (s) => s.trim().replace(/\s+/g, " ").toLowerCase();
console.log(normalise(actual) === normalise(expected));🖥️ Output
trueQ6. Write isMissing(value) in one line that returns true only for null and undefined.
Show answer
📄 practice6.js
const isMissing = (value) => value == null;
console.log(isMissing(null), isMissing(undefined), isMissing(0), isMissing(""));🖥️ Output
true true false falseThis is the one place where == is commonly accepted, because null is loosely equal only to undefined. value === null || value === undefined is the explicit equivalent.
🧠 MCQ Quiz: Truthy, Falsy and Equality
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- How many falsy values does JavaScript have?Answer: 8. false, 0, -0, 0n, “”, null, undefined and NaN.
- Which value is truthy?Answer:
[]. All objects, including empty arrays and empty objects, are truthy. - What is
"1" == 1?Answer:true. Loose equality converts the string to a number first. - What is
"1" === 1?Answer:false. Strict equality also compares types: string vs number. - What is
null == undefined?Answer:true. They are loosely equal to each other and to nothing else; strictly they are different. - What is
NaN === NaN?Answer:false. NaN is never equal to itself; useNumber.isNaNorObject.is(NaN, NaN). - What is
{ a: 1 } === { a: 1 }?Answer:false. Two different objects are never strictly equal, whatever their contents. - Which assertion should you use to compare two objects by content in Playwright or Jest?Answer:
toEqual.toBechecks identity with Object.is;toEqualchecks contents. - What does
!!"false"return?Answer:true. Any non-empty string is truthy, including “false”. - What is
"10" < "9"?Answer:true. Both are strings, so they are compared character by character: “1” comes before “9”.
💼 Interview Questions and Answers
Q1. What is the difference between == and ===?
=== (strict equality) compares type and value without conversion. == (loose equality) converts the operands to a common type first, which leads to results such as 0 == "" and "0" == false being true. Use === by default; the only common exception is x == null to check for both null and undefined.
Q2. List the falsy values in JavaScript.
false, 0, -0, 0n, "", null, undefined and NaN (plus the legacy browser object document.all). Everything else is truthy, including "0", "false", [], {} and negative numbers.
Q3. How do you compare two objects or arrays for equality?
With === you only learn whether they are the same reference. To compare contents, use a deep-equality function: assert.deepStrictEqual or util.isDeepStrictEqual in Node.js, toEqual/toStrictEqual in Jest and Playwright, or a library such as Lodash’s isEqual. JSON.stringify comparison is a fragile shortcut because key order and undefined values affect it.
Q4. Explain why null >= 0 is true but null == 0 is false.
Relational operators (>=, <) convert null to the number 0, so 0 >= 0 is true. Equality == has a special rule: null is only loosely equal to undefined, so it is never converted to 0 there. It shows why mixing loose comparisons with nullable values is risky.
Q5. A test checks if (response.data) before asserting, and the test still passes when the API returns no data. What is wrong?
An empty array is truthy, so the block runs but may assert nothing useful; and if data is 0, "", null or missing, the block is skipped and the test passes without checking anything. Conditional assertions hide defects. Assert unconditionally on what you expect (expect(response.data).toEqual([...]) or expect(response.data.length).toBeGreaterThan(0)), so a missing or wrong value fails the test.
❓ Frequently Asked Questions
🤔 Should I always use === in JavaScript?
Yes, as a rule. It is predictable and catches type mismatches. Use x == null only if your team accepts it as shorthand for “null or undefined”.
🤔 Why is [] == false true but [] is truthy?
They use different rules. In a condition, every object is truthy. With ==, the array is converted to a primitive ("") and then to a number (0), and false also becomes 0.
🤔 How do I check if an object is empty?
Use Object.keys(obj).length === 0. Checking if (obj) does not work because every object is truthy.
🤔 What does !! do in JavaScript?
It converts any value to its boolean equivalent: !!"text" is true, !!0 is false. It is the same as Boolean(value).
🏁 Summary
- The 8 falsy values are
false,0,-0,0n,"",null,undefinedandNaN; everything else, including[]and{}, is truthy. - Truthiness checks treat
0and""as missing; compare explicitly when those are valid values. ==converts types before comparing;===does not. Use===.- Objects and arrays are equal only if they are the same reference; use deep equality (
toEqual,deepStrictEqual) for contents. - Normalise strings (trim, case) before comparing UI text, and convert numeric strings before comparing numbers.
Next, continue with Lesson 11: Optional Chaining and Nullish Coalescing.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in