JavaScript: What's the output

For each given JavaScript code snippet, determine the correct output to the console. Warning: these questions largely test for quirks of syntax which you have hopefully never had to encounter before.
Quiz by Irratix
Rate:
Last updated: February 3, 2022
 First submitted February 3, 2022 Times taken 95 Average score 33.3% Report this quiz Report
40:00
The quiz is paused. You have remaining.
Scoring
You scored / = %
This beats or equals % of test takers also scored 100%
The average score is
Keep scrolling down for answers and more stats ...
1. let x = 1;
console.log(x++);
x++ returns x before incrementing.
2. console.log(0 || 5);
The || operator returns the first argument if it is truthy, otherwise it returns the second argument.
3. console.log(-1 / 0);
1/0 returns Infinity, so its negative returns -Infinity.
4. let x = 3, y = 5;
console.log(x ^ y);
^ is the bitwise XOR operator. 11 XOR 101 = 110.
5. let s = "";
for (const i in [0,0,0])
s += 1 + i;
console.log(s);
A for (.. in ..) loop loops over the keys of the object as strings, so this loops over the strings "0", "1" and "2".
6. console.log(! 5 < 6);
Operator precedence: !5 gets evaluated first, which becomes false. false < 6 is true.
7. console.log("" + Array(10));
Adding an array to a string joins the array by commas. All elements are empty, so this just becomes a string of 9 commas.
8. let s = "";
for (let i = 5; i--, i > 0; )
s += i;
console.log(s);
The conditional of the loop contains two separate expressions. The conditional gets evaluated as first step of the loop after the initialization. Both expressions get evaluated, but only the latter actually functions as a condition to terminate the loop.
9. const x = 1n;
console.log(x + 1);
1n is a BigInt. Adding a BigInt to a Number is not allowed, so this gives an Uncaught TypeError.
10. console.log(![]);
For some reason arrays are always truthy, even when they are empty.
11. console.log(011);
Prefixing a number with a 0 makes it octal.
12. const x = {
a: 1,
a: 2
};
console.log( JSON.stringify(x) );
JSON format requires the key to be between quotation marks. "a":1 gets overwritten by "a":2.
13. const x = "x" - 1;
const y = "y" - 1;
console.log(x == y);
Subtracting a number from a string that cannot be parsed to a number returns NaN. NaN == NaN is false.... somehow.
14. console.log(5 - 3 + "e2" - 1);
This gets evaluated from left to right. 5 - 3 == 2. 2 + "e2" == "2e2". 2e2 is exponential notation, which can be parsed from a string to a number, and becomes 200. Therefore "2e2" - 1 == 200 - 1, and 200 - 1 == 199.
15. // WARNING: hard
let s = "";
for (let i = 5, j = 0, r = 1; j += r *= j < i || -1;)
s += j;
console.log(s);
So long as r remains equal to 1, j gets incremented by 1 over every iteration. When j == 5, j < i will be false. At this point r will be multiplied by -1. From that point on, j will decrement until it reaches 0 and the loop exits.