1

Returns undefined. How ever if i console.log inside the map function that prints right value.

const myfun = (data) => {
    data.map((elem) => {
      return elem[1]  
    });
  };
  
  
let demo = [[1,2,3],[1,2,3]]
  
console.log(myfun(demo)); 
// gives undefined
// should give 2 2
geek glance
  • 111
  • 2
  • 9
  • 3
    `myFun` doesn't have a `return` statement. Either add one or remove the `{` and `}` from the body. – VLAZ Aug 24 '21 at 06:42
  • 1
    `myFun` could be written on one line: `const myFun = (data) => data.map(elem => elem[1])`. This will implicitly return the result of `data.map(...)` – Yousaf Aug 24 '21 at 06:44
  • `const myfun = (data) => data.map((elem) => elem[1])` one line answer – Manjeet Thakur Aug 24 '21 at 06:49

2 Answers2

2

Yes your function returns nothing, therefore undefined.

I think what you meant to write was this.

const myfun = (data) => (
    data.map((elem) => {
      return elem[1]  
    })
);

notice how the myfun function is not using curly braces instead it's using regular brackets.

or this.

const myfun = (data) => data.map((elem) => {
      return elem[1]  
    })

If you use curly brackets on an anonymous function you must explicitly use the return keyword.

masonCherry
  • 894
  • 6
  • 14
  • Regular brackets are not needed. – VLAZ Aug 24 '21 at 06:44
  • Yes, they are not required I've included an example without them. sometimes however you do need them. in case you are returning an object literal `const x = () => ({})` . – masonCherry Aug 24 '21 at 06:50
1

This happens because you need to return the map, not just what is mapped

const myfun = (data) => {
    // You need to return the map
    return data.map((elem) => {
      return elem[1]  
    });
  };
  
  
let demo = [[1,2,3],[1,2,3]]
  
console.log(myfun(demo)); 
StudioTime
  • 22,603
  • 38
  • 120
  • 207