Did not fully understand how map() works

I was wondering if anyone could explain why this is not working the output for
console.log(a) is
[ undefined, undefined, undefined, undefined, undefined, undefined ]
I did not really understand how map() function works and how it is different from for loop.

I thought the output would be []

Your code so far


function bouncer(arr) {

let a= arr.map(i=>{
  if (i)
  {
   return i;
  }
})
console.log(a)
return a

}
bouncer([false, null, 0, NaN, undefined, ""])

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15.

Challenge: Falsy Bouncer

Link to the challenge:

Hello!

The map function transforms creates a new array from the items returned from the function callback.

The problem with your solution is that it’s called for each item, mapping that item to a new one. When you don’t return a value, the default return value is undefined, hence your result.

Does it help?

1 Like

Hello there,

This is from Mozilla about the return of the .map method:

A new array with each element being the result of the callback function.

So, you have a function here:

function anon(i) {
  if (i)
  {
   return i;
  }
}

What is the result of calling this with?:

anon(false)
1 Like

is it undefined ? since it wont enter this

if (i)
  {
   return i;
  }

it will return undefined ?

Exactly. It is the same reason this console.logs undefined:

function myFunc() {
  // I do not return anything
}
console.log(myFunc()); // In console: undefined
2 Likes