4

What's the difference between these two in javascript? what does it mean in scripting?

const Test1 = () => {
    console.log('test1')
}


const Test2 = () => (
    console.log('test2')
)
totalnoob
  • 2,521
  • 8
  • 35
  • 69

2 Answers2

5

The "basic" form is with curly braces, just like regular functions:

() => {
    ...
}

However, arrow functions allow one special case shorthand:

() => plain expression

If you don't use curly braces, you may use one plain expression instead, with an implicit return. I.e. these two are equivalent:

() => { return 42; }
() => 42

So your version using parentheses counts as the single expression version and the return value of console.log will be returned (which is undefined either way though), whereas it won't on the version using curly braces.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

Second example used to simplify returning of function, but in this case you can use only one expression, so you cannot write large of code. Try to run this example to better understand:

const Test1 = () => {
   'test1'
}

console.log(Test1())


const Test2 = () => (  test = 'test4')

console.log(Test2())

Also this declaration method uses to simplify returning objects:

const Test3 = () => ({ a: 1, b: 2 });
console.log(Test3());
Artem Mirchenko
  • 2,140
  • 1
  • 9
  • 21