Javascript Interview Question: Why does [9,8,7,6][1,2] = 7 ?

JavaScript Puzzles Unveiled: A Closer Look at Unexpected Array Operations in Interviews

Photo by Brooke Cagle on Unsplash

To cut it short, here is the question. What will be logged in the console when we run this code snippet?

.

.

.

When we run this code snippet the value res will be 7 . And 7 will be logged in the console.

Let’s Break this down.

Step 1: [1,2] This will be converted into [2].

Why?

The subsequent element [1,2] cannot function as an array; hence, it operates as an array subscript. In the context of a subscript operation, the contents do not constitute a delimited list of operands but rather a singular expression.

In javascript, we can write expressions separated by a comma (,). and the result of the last expression will be returned.

// Example 1
const z = (1,2,3,4,5);
console.log(z); // outputs 5

// Example 2
function a() {
return 'a';
}

function b() {
return 'b';
}

function c() {
return 'c';
}

const d = (a(), b(), c());
console.log(d); // Outputs 'c'

Step 2: After the above code becomes [9,8,7,6][2] which is straightforward, we are trying to access the element at 2 index, which is 7.

Here are more variations:

[9,8,7,6][1,2,3] // outputs 6
[9,8,7,6][8,2,3,1] // outputs 8

--

--