Interesting JavaScript Interview Question

What is the output of following piece of code?

const a = [0, 1, true, 'asdf'];
const b = a.forEach(val => val * 2);

The simple answer for this question is: undefined

However to get to this answer you have to demonstrate that you are knowledgeable in a wide range of JavaScript specific topics.

In an interview - you should demonstrate this knowledge let’s take a look what all you can say about this piece of code.

The Array

The first thing, is that you have an array with mixed types. [number, number, boolean, string]. This is valid in JavaScript. However this is a very bad coding style and can create unwanted bugs if you encounter a type mismatch. This kind of code should be avoided in any production code if possible.

Additionally you can mention TypeScript, as when this array at least is typed it will directly highlight potential problems like in the next step.

The Loop

First you have to think about what happens for each type * 2 (i.e. will an error be thrown)

  • the numbers will be multiplied
  • the boolean true will be converted to a 1 and multiplied
  • the string is NaN

The forEach() function returns undefined, in order to fix this piece of code you would have to use the map() function.

The Output

While not strictly important, but there is actually no need to use console.log in this instance, the question also could be What value has b?

You could have a short discussion about the pros and cons using console.log in production, and about how you could debug this using the debugging tools. Or alternatively how you would write a test case using a testing framework.

Overall just remember, in every part of a technical interview you can demonstrate a wide range of skills, even if the question initially was rather simple and straightforward. - Communication is key during an interview.