Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Arrow function without curly braces

I'm having a hard time understanding the following ES6 syntax. I read the docs quite a bit and it seems like there is more than one change happening here:

const renderInput = props =>
  <div>
    <label>{props.placeholder}</label>
  </div>

Would the above be equivalent to:

const renderInput = function renderInput(props) {
  return <div>
           <label>{props.placeholder}</label>
         </div>
}

?

like image 808
softcode Avatar asked Jan 07 '17 21:01

softcode


People also ask

Do arrow functions need curly braces?

There are two ways to declare an arrow function: Without curly braces {} . With this syntax, the arrow function has an implicit return. For example, the below arrow function returns 42, even though there's no return .

When should you not use arrow functions in ES6?

An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.

What does => mean in ES6?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

How are arrow functions () => {} different than traditional function expressions?

Unlike regular functions, arrow functions do not have their own this . The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.


1 Answers

Yes, that is correct. When you have only one expression, and it's the expression you wish to return from the function, you may omit the curly brackets.

Since <div><label>{props.placeholder}</label></div> is, in fact, a single expression (it gets transpiled to React.createElement(......) or something like that), and you wish to return it from renderInput, that is indeed how you use the no-brackets version of the arrow function.

If you had wished to use variables or do some other computation (conditions, for loops, etc), you wouldn't have been able to omit the brackets.

like image 164
Madara's Ghost Avatar answered Sep 28 '22 16:09

Madara's Ghost