Javascript Developer JSE 40 01 · Free Practice Question Easy
Question 17
Q523 - Control Flow
Examine the following code:
- let route = {distance: 131, elevation: 1.4};
- for (let k in route) console.log(k);
What will appear in the console as a result?
-
A
- 131
- 1.4
-
B
- 2
-
C
- distance
-
D
- distance
- elevation
Reveal correct answer
Correct answer: D
Explanation
Topic: for in over object
Try it yourself:
- let route = {distance: 131, elevation: 1.4};
- for (let k in route) console.log(k);
- // distance
- // elevation
Explanation:
The for in statements combo iterates over the properties of an object.
The code block inside the loop is executed once for each property.
https://www.w3schools.com/jsref/jsref_forin.asp
(There are similar questions Q323 and Q423.)
Q523 (Please refer to this number, if you want to write me about this question.)
A. This choice is incorrect because the for...in loop in the code logs the keys of the 'route' object, not the values. Therefore, the output will show 'distance' and 'elevation' as the keys, not the values ('131' and '1.4').
B. This choice is incorrect because the code does not output the number '2'. The for...in loop iterates over the keys of the 'route' object, not the values, so the output will only display the keys 'distance' and 'elevation'.
C. This choice is incorrect because the for...in loop in the code logs the keys of the 'route' object, not the values. Therefore, only the keys ('distance' and 'elevation') will be displayed in the console, not the values.
D. The code iterates over the properties of the 'route' object using a for...in loop, which logs each property key (k) to the console. Therefore, the output will display 'distance' and 'elevation' on separate lines as they are the keys of the 'route' object.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
