What is val parameter how it is cakled or passed?

Continuing the discussion from freeCodeCamp Challenge Guide: Filter Arrays with Filter:

If you are referring to the use of val in the following code:

var array = [1,2,3,4,5,6,7,8,9,10];
  // Only change code below this line.
array = array.filter(function(val) {
  return val <= 5;

then I will refer you to the MDN Documentation for Array.prototype.filter. If you still have questions after reading the documentation, reply back to this post with your question(s).

i passed the challenge. But still stuck with How does this “function(val) and return val;” works.

The filter function iterates through an array by using a callback function which has access to 3 arguments (and a 4th which I won’t go into here).

The 3 arguments (in order) are:

  1. the current array element
  2. the index of the current element
  3. the original array the filter function was called upon

You can use one or more of these arguments by creating parameter variables in the function declaration. In the example in my previous post, we use an anonymous function with parameter called val. Since val is the first parameter, then it will have access to the current array element value. The other 2 arguments are not used in this example, so they are not listed as parameters.

val is just a variable name used in the function to represent the current element. We could have called it theArrayElement or element or another name which gives a description of what data it contains. As long as you use that same name in your function you will be fine.

The filter function always returns a new array with only the elements of the original array where the function returned the value true. In our example:

  return val <= 5;

will return a true or false value depending on whether or not the current element being accessed is less than or equal to the value 5.

Since values 1-5 will evaluate to true in the return statement, filter will return a new array that looks like:

[1, 2, 3, 4, 5]

Hopefully, you now have a better understanding of what filter does and how val was used to get the desired result.

1 Like


I don’t understand why ES6 doesn’t works here but on previous exercice yes ?

var newArray = oldArray.filter(element => element.length < 6);

the same as

var newArray = oldArray.filter(function(element) {
    return element < 6;