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.

0

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.