Reputation: 759
I am relatively new to Javascript and am working through ch. 5 of Eloquent Javascript. I came across some code that I don't quite understand. I know HOW it works (the general method and steps), but I don't understand WHY it works.
The code is here:
function filter(array, test) {
var passed = [];
for (var i = 0; i < array.length; i++) {
if (test(array[i]))
passed.push(array[i]);
}
return passed;
}
Basically the function takes the element the 'for loop is iterating over' from the array, and compares it to the test parameter.
I am wondering how/why this works:
if (test(array[i]))
There is no || && or other 'comparison operators'. How does it compare values with only using parenthesis?
How is test compared to the array[i] value with no operators?
Link to file: http://eloquentjavascript.net/05_higher_order.html go to 'Filtering an Array' exercise
Thanks!
Upvotes: 2
Views: 173
Reputation: 94
'test' here is a function, not a value. In Javascript, each function is an object and can be passed as parameter. In this case, test is a function that take one parameter and return true or false base on the parameter value.
So in the for loop, test function is called with each array element and if the result is true, it will be store in another array. Eventually, passed elements would be return to the function caller.
Upvotes: 0
Reputation: 10536
Whatever is inside the parentheses of an if
statement will be evaluated. If the result is falsy (false
, 0
, ""
, NaN
, null
, undefined
) it fails and if the result is truthy (everything else) it passes. So if your if statement contains a function call if (test(something)) {}
, then the if statement just says if the result of the function call is truthy then pass
.
Also, &&
and ||
are not comparison operators, they are boolean operators. They just connect the result of two statements, like true || false
which evaluates to true
.
Upvotes: 3
Reputation: 114579
This code is accepting a test
parameter that is what is called a "predicate function" i.e. a function that given an element will return true or false.
It's going to be used for example with
var big_numbers = filter(numbers, function(x){ return x > 100; });
i.e. the expected parameter test is actually code.
In Javascript passing code is very common and idiomatic. It's something that is more annoying in other languages that don't support the concept of "closure" and of "nested function", forcing all code to live at the top level, being given a name and to have no context (e.g. the C language).
Upvotes: 0
Reputation: 695
I am not quite sure, but I think this is a custom function. Most likely there is some comparison there and the result of the function is True/False. If you give us the whole code we could explain it better to you.
Upvotes: 0