Why doesn't this code output an error since "a" is not defined? Also, why does it output 2 since 1 is the first element? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why doesn't this code output an error since "a" is not defined? Also, why does it output 2 since 1 is the first element?

var c = new Array(1,2,3,4); var b = c.filter(function(a) { return(a%2-1); }); alert(b[0]);

27th Jun 2019, 2:36 PM
eMBee
eMBee - avatar
7 Answers
+ 4
With numbers converted to boolean, ONLY 0 is false, even negative numbers are true
27th Jun 2019, 2:54 PM
Airree
Airree - avatar
+ 6
"a" is an argument that filter gives to it's internal function. If this internal function returns a true value, it will apply to output variable (here is "b") In c array, the first element that applying (a%2-1) statement on it will output true is 2 so first element of "b" is 2.
27th Jun 2019, 2:52 PM
Qasem
+ 5
Airree, I'm afraid to say that I still don't understand your explanation 🤦‍♂️
27th Jun 2019, 2:45 PM
eMBee
eMBee - avatar
+ 5
Okay @Airree after taking a closer look at your explanation, I think understand it but I don't understand how -1 is true?
27th Jun 2019, 2:53 PM
eMBee
eMBee - avatar
+ 4
The filter method is an interesting one: it's a high-order function. It runs the function on every element of the array, and keeps the element if the function returns true. You can basically break the filter method down like this: function filter(array, func) { let temp = []; for (let i of array) if (func(i)) temp.push(i); return temp; } a isn't undefined, because it is a function parameter. So if we look at it with the first element (1): function filter(a) { return a % 2 - 1; } console.log(filter(c[0])); //Output: 1 % 2 - 1 = 0, which is falsely, therefore the first element will be filtered out of the array console.log(filter(c[1]) //Output: 2 % 2 - 1 = -1 (truthy) -> it stays
27th Jun 2019, 2:40 PM
Airree
Airree - avatar
+ 3
Well, what do you don't understand?
27th Jun 2019, 2:45 PM
Airree
Airree - avatar
- 1
It is a basic concept of Boolean values: 0 = False. Every other value is true. Try writing a small program to test it out.
28th Jun 2019, 12:04 PM
Rick Henderson
Rick Henderson - avatar