DEV Community

Cover image for JS Test #11: Scope
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JS Test #11: Scope

js-test-11

Variables with the same name in JavaScript? What will be logged to the console?
.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In the first line, we see an array animals that holds 5 strings.

The length of this array is used in the loop condition, so the loop will continue spinning up to the point when i becomes equal to 5.

Inside of the loop, a new array is declared with the same name animals. There are no issues with such a declaration and no errors will be thrown.

It’s important to remember, though, that the value animals.length in the loop condition is attributed to the external array with 5 elements but the console.log picks up the inner array, which has only 2 elements in it.

Once we go out of bounds there will be no error like in C++ or Java. Instead, we’ll get undefined as the result of the last 3 iterations of the loop.


ANSWER: The strings Whale, Dolphin will be logged to the console, followed by undefined, undefined, undefined.

Top comments (0)