Interview questions can sometimes be deceptively simple, like this one:
let arr = [0, 1, 2, 3];
let count = 0;
arr.forEach((element, index) => {
if (element) {
count++;
}
});
console.log('count', count);
At first glance, this code seems straightforward, but there’s a subtlety that can trip up even experienced developers. Let’s break it down step by step.
Question
What will be logged to the console when this code is executed? And why?
Explanation
1. Initialization
We start with an array arr containing the values [0, 1, 2, 3] and a variable count initialized to 0.
2. Iterating Over the Array
The forEach method iterates over each element of the array. For every iteration, the element variable holds the current array value, and index holds the current index (though index isn’t used in this example).
3. The Conditional Statement
The condition if (element) checks whether element is truthy. In JavaScript:
- Truthy values: Non-zero numbers, non-empty strings, objects, arrays, etc.
- Falsy values:
0,null,undefined,false,NaN, and an empty string ('').
Here, the values in arr are 0, 1, 2, 3. When evaluated in a Boolean context:
0is falsy.1,2, and3are truthy.
4. Counting Truthy Elements
Whenever element is truthy, the condition if (element) evaluates to true, and the code inside the block — count++ — is executed, incrementing count.
5. Final Result
Only three values in the array are truthy (1, 2, 3). Hence, count is incremented three times.
The final output is:
count 3
Key Takeaways
- Understanding Truthy and Falsy Values: Many JavaScript interview questions test your knowledge of what is considered truthy or falsy in different contexts.
- Iterating with
forEach: This method is often used to perform operations on array elements, so it’s important to understand how it works. - Attention to Detail: Simple-looking code can have nuances that reveal your depth of understanding of JavaScript basics.
Bonus Question
What happens if we change the array to include other falsy values, like this?
let arr = [0, false, '', NaN, undefined, null, 1, 2, 3];
How does count change? Try it out and explain the result in the comments section!
Do you have a favorite tricky interview question? Share it below, and let’s discuss!
No comments:
Post a Comment