JavaScript Coercion and Equality Code Traces
Six output traces drilling on `==` vs `===`, unary `+`, falsy values, and chained relational coercion. Sharpens the rules JS applies before comparing.
Question Bank
Easy
JavaScript
6 questions
quiz
interview-prep
fundamentals
js-language
441 views
10
What does the following code print?
Examples
Example 1:
Input: console.log(a == b); console.log(a === b);
Output: false; false
Explanation: Arrays are objects, so both == and === compare by reference identity, and a and b are two distinct array instances.const a = [1, 2, 3];
const b = [1, 2, 3];
console.log(a == b);
console.log(a === b);What is the output of the following code?
Examples
Example 1:
Input: console.log(0 == '0'); console.log(0 === '0');
Output: true; false
Explanation: == coerces the string '0' to the number 0 before comparing, while === requires identical types and a number is not a string.const number = 0;
const str = '0';
console.log(number == str);
console.log(number === str);What does the following code print, line by line?
Examples
Example 1:
Input: log(+'0'); log(+'false'); log(+1); log(+'1'); log(+''); log(+true); log(+false); log(+'foo');
Output: 0; NaN; 1; 1; 0; 1; 0; NaN
Explanation: Unary + applies Number(x) semantics, so numeric strings and booleans coerce cleanly while non-numeric strings become NaN.const log = console.log;
log(+'0');
log(+'false');
log(+1);
log(+'1');
log(+'');
log(+true);
log(+false);
log(+'foo');Trace the output of each console.log below.
Examples
Example 1:
Input: undefined + 1; undefined == null; undefined === null; null * 2; null * null; 1 === true
Output: NaN; true; false; 0; 0; false
Explanation: undefined coerces to NaN in arithmetic and null coerces to 0, while undefined == null is a special spec rule and === never coerces.console.log(undefined + 1);
console.log(undefined == null);
console.log(undefined === null);
console.log(null * 2);
console.log(null * null);
console.log(1 === true);What does each line below print?
Examples
Example 1:
Input: ![] == 0; [] == ![]; '1' == 1; '01' == true
Output: true; true; true; true
Explanation: Each comparison reduces to 0 == 0 or 1 == 1 after == coerces booleans, arrays, and strings into numbers.console.log(![] == 0);
console.log([] == ![]);
console.log('1' == 1);
console.log('01' == true);Predict the output and explain why chained relational operators behave this way.
Examples
Example 1:
Input: 5 < 6 < 7; 7 > 6 > 5
Output: true; false
Explanation: Relational operators are left-associative, so the first inner comparison yields a boolean that coerces to 1 or 0 before the next comparison runs.console.log(5 < 6 < 7);
console.log(7 > 6 > 5);