Assessment wanted for Functions 4 skill test


in functions 4 this line of code causes a doubt:
const shortNames = names.filter(isShort);

You are passing a function to filter() without parenthesis to not immediately call it. You have to pass it to filter(), even though it is global, because filter() is defined somewhere else.

My question is - isShort(name) needs a parameter ‘name’. Why can you omit the parameter here? Does filter() see that it needs some parameter and since filter goes through the array like a for each loop, item for item, it just passes each item to isShort(name) by default?

Many thanks!

You can omit the parameter because the following code is equivalent:

names.filter(function (x) { return x.length < 10 })
// is equivalent to
let isShort = function (x) { return x.length < 10 }

We never “tell” filter() how many arguments isShort takes. filter() will just call isShort with every item as its single argument ie. isShort(element) – regardless of how many arguments isShort “requires”.

On function arguments

In Javascript, if you pass too few arguments to a function, the missing arguments are set to undefined. If you pass too many, they’re just not used.

function wantsTwoArgs(arg1, arg2) {
    console.log(arg1, arg2)

wantsTwoArgs("hello", "mdn") // -> "hello" "mdn"
wantsTwoArgs("hi") // -> "hello" undefined
wantsTwoArgs("greetings", "all", "humans") // -> "greetings" "all"

Moreover, if you look at the docs for filter() (on MDN), you’ll notice that the filter function can have three function signatures:

// Arrow function
filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )

Which means that within filter(), isShort is probably being called as isShort(element, index, array). But since isShort only uses one argument, the index and array parameters are ignored.

I hope this made sense and I didn’t make things even more confusing.


Hey, thanks for the fast answer. That makes it clear!