This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for JavaScript Quiz on BFE.dev
5. scope
The code will output:
5
5
0
1
2
3
4
The first for
loop uses a var
declaration for i
, which has function scope and is hoisted to the top of the function. As a result, when the setTimeout
callbacks are executed, they all refer to the same i
value, which is 5
at the end of the loop.
The second for
loop uses a let
declaration for i
, which has block scope and is not hoisted. As a result, each iteration of the loop creates a new i
variable with a new value that is captured by the corresponding setTimeout
callback. Therefore, the callbacks output 0
, 1
, 2
, 3
, 4
in sequence.