Consider the following code snippet:
var numbersArray = [1, 3, 6, 8, 11];
var returnedArray = numbersArray.filter(function(number) {
const condition = false // or true sometimes
return number > 7 && condition ;
});
console.log(returnedArray); // Result is : []
The outcome of the code above will be an empty array [];
Since the condition
variable is set to false, the result is as expected to be empty.
It may seem confusing, but as per Mozilla MDN, the filter()
method creates a new array by filtering elements based on a provided function.
However, in this case, the condition variable is not directly related to the array's elements.
For a clearer explanation, let's break it down for a junior developer like myself.