0
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = numbers.filter(function evenNumbers (number) {
  return number % 2 === 0;
});

console.log(filtered);

I am total beginner to JavaScript, picking up the course offered by nodeschool. While in the exercise of "ARRAY FILTERING", I wonder what is the role of 'number' within the function evenNumbers as it was not declared beforehand.

vizFlux
  • 735
  • 2
  • 9
  • 14

2 Answers2

1

It is declared, as a formal parameter to the callback evenNumbers (a function that takes an argument and tests whether it is even). filter will call the callback function once for each element of the array numbers, providing the element as the argument to the callback (which will assign it to number, via the usual function invocation process).

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • So that means 'number' in the function representing the arrays within the 'numbers', which declared in the very beginning, and the function is filtering the numbers based on 'evenNumbers'? @Amadan – vizFlux Aug 24 '15 at 04:01
  • `evenNumbers` is the criterion for `filter`. You ask `evenNumbers(1)`, it says `false`. `evenNumbers(2)`, and it says `true`. `filter` will append each element to the result or not depening on what the callback function says; so `1` is not appended, and `2` is appended. Thus, the result ends up `[2, 4, 6, 8, 10]` with `1`, `3`, `5`, `7` and `9` missing. – Amadan Aug 24 '15 at 04:03
0
  1. numbers is an Array
  2. .filter is a method declared on Array.prototype
  3. .filter method accepts a callback function.
  4. Internally it looks Like,

,

Array.prototype.filter(callback[, thisArgs]) {
    '''''
    '''''
    callback(currentElement, index, arrayObjectBeingTraversed)
}); 

So,

In your case,

callback  --> function evenNumbers() {}

currentElement --> Number

More about Javascript Callback Functions

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79