score:3

Accepted answer

because the arrow function

todo => {
    <li key={todo.id}>{todo.name}</li>
}

returns nothing and you will get an array that contains undefineds ( based on the length of todos). for example:

const ary = [1, 2, 3].map(el => { console.log(el) })
console.log(ary) // [undefined, undefined, undefined]

you must return something in the callback of .map()

if the callback only contains 1 expression and returns immediately, you can omit the { } and return.

const foo = () => {
  return 'foo'
}

is equal to

const foo = () => 'foo'

so now you can:

const todolist = ( {todos} ) => (
    <ul>
        { todos.map( todo => (
            <li key={todo.id}>{todo.name}</li>
        ))}
    </ul>
)

also the ( ) is not a must, you can omit that if you preferred:

const todolist = ( {todos} ) => (
    <ul>
      { todos.map(todo => <li key={todo.id}>{todo.name}</li>) }
    </ul>
)

score:0

the difference has to do with how you specify the body of the arrow function.

{ todos.map( todo => 
    <li key={todo.id}>{todo.name}</li>
)}

is an expression within the body and by default does not need a return statement,

  <ul>
    { todos.map(todo => <li key={todo.id}>{todo.name}</li>) }
  </ul>

when defined within a block, a return statement needs to be included .

score:0

here, you nicely added a block statement , in block statement implicit return is syntactically ambiguous, now it returns undefined. in es6 arrow function return is implicit under some circumstances. like you added a block it made undefined. you can find more detail in this post.

score:0

if you look at the documentation for map, you have to return a value, which will be the new value in the new array created by the map function. this means that return has to exist in the callback of your map function, whether stated explicitly or implicitly.

the arrow functions you have declared as a callback (e.g todo => <li key={todo.id}>{todo.name}</li>) in the first and the second example are equal. you may want to refer to different ways to declare arrow functions in the documentation here.

in the third example however, you are returning a block of code without a return statement. the default behavior of the javascript runtime is to return undefined. here are some code to demonstrate this behavior:

const test = () => { var a; /* a block of code with no return statement */ }

const a = test();

console.log(a);

hence, the elements of the array that is returned from the map function in your third example will undefined. this is the main reason why your todos are not getting rendered in your list.


Related Query

More Query from same tag