Javascript Practice

why does this keep returning undefined

function justCoolStuff(firstArray, secondArray) {firstArray.filter(item =>
secondArray.includes(item)
)}

when this works

const justCoolStuff = (firstArray, secondArray) => firstArray.filter(item =>
secondArray.includes(item)
)

is function ~~() not a valid method or something? This is happening to me every time.

Hi, welcome to the forums :slight_smile:

Please see formatting guidelines here: [How to] Format code in posts

As to your question. Functions need to return things (even if that thing that is returned is nothing). The key is that in different ways of writing functions, you will get implicit returns sometimes and sometimes not, depending on the type of definition. [And again, by functions needing to return things, it doesn’t mean we actually have to give them things to return, it’s just the way the programming language works and is fairly common, it’ll be more clear with the examples].

For the type that is written

function f(x){
    return x;
}

you need to explicitly return x.

If you do a one-liner type of arrow function you can write

const g = (x) => x;

for the same effect. The return type here is implicit since you are not explicitly instructing the compiler to return x.

Constrast this with a multi-line arrow-function

const h = (x) => {
   console.log("foo");
   console.log("bar");
   x;
}

this last function will not return x because the moment you make it multi-line you have to explicitly state what you want to return. However, the function will return undefined as a vacuous output.

f(5) // returns 5
g(5) // returns 5
h(5) // returns undefined