- Published on
What is the output of following piece of code?
const a = [0, 1, true, "asdf"] const b = a.forEach((val) => val * 2) console.log(b)
The simple answer for this question is:
In an interview - you should demonstrate this knowledge let's take a look what all you can say about this piece of code.
Additionally you can mention TypeScript, as when this array at least is typed it will directly highlight potential problems like in the next step.
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
forEach() function returns
undefined, in order to fix this piece of code you would have to use the
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.