CodePeek · Free JavaScript classroom challenge
What does it print?
TEACHER KEY · Answers and explanations
Same snippets and order as the learner handout and interactive quiz. Keep this key separate until learners have made their predictions.
1. String coercion
console.log(1 + "2" + 3);Correct output
123- The first + has a string operand, "2", so 1 becomes a string and the result is "12".
- Operators at this precedence are evaluated left to right. "12" + 3 concatenates again, producing "123".
- console.log prints the string as 123. Quotes in the source mark a string; they are not part of its contents.
Takeaway: + can add numbers or join strings. Check the operands before you add.
2. Numeric coercion
console.log("5" - 2);
console.log("5" + 2);Correct output
3
52- Subtraction converts "5" to the number 5, so 5 - 2 is 3.
- + with a string operand concatenates: "5" + 2 is "52".
- The two console.log calls print on separate lines, in source order.
Takeaway: Unlike +, subtraction is a numeric operation.
3. Equality
console.log(0 == false);
console.log(0 === false);Correct output
true
false- Loose equality converts false to 0, so 0 == false is true.
- Strict equality does not coerce types. A number and a boolean are different types.
- The second comparison therefore prints false.
Takeaway: === compares without type coercion.