Operators & type coercion
Computer Science · JavaScript
Question 1 of 10
0What does this JavaScript code log? console.log(47 === "47");
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Operators & type coercion explained
JavaScript converts values to other types automatically when an operator needs a different type. This is called coercion, and it causes many surprising results, which is why the strict operators === and !== are preferred.
The + operator concatenates when either operand is a string. The other arithmetic operators, such as minus, times and divide, convert their operands to numbers. Values such as 0, the empty string, null, undefined and NaN are falsy, so they behave as false in a condition.
console.log("5" + 3 - 2);
console.log(1 + 2 + "3");
console.log("5" == 5, "5" === 5);
The loose operator == converts types before comparing, which makes results hard to predict. The strict operator === compares both value and type. NaN is not equal to anything, including itself, so use Number.isNaN to test for it.
Worked example
Trace "5" + 3 - 2 from left to right. "5" + 3 is the string "53", because + sees a string. Then "53" - 2 converts "53" to the number 53, giving 51. The program prints 51, then 33 for 1 + 2 + "3", then true and false.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this JavaScript code log?
console.log(61 === "61");
- TypeError
- true
- undefined
- false
Medium
What does this JavaScript code log?
const r = 4 + 2 + "1" - 1; console.log(r);
Hard
How many of these comparisons are true? The array holds the results.
const tests = [[1] == 1, [] == false, null === undefined, null >= 0, null == 0]; console.log(tests.filter(Boolean).length);