0

Long story short when working in React, there are situations when I have to use arrow functions with () instead of {} and vice-versa.

const foo = (item) => ( ... );

and

const foo = (item) => { ... };

My code is often failing because I am confusing them. What, I am trying to understand is the difference between the two arrow functions. What are the best-case scenarios for both?

Many thanks!

2 Answers 2

3

Arrow function without curly braces return the function expression. Example:

() => 'Hello world';

will do the same as

function() {
  return 'Hello world';
}

If you use curly braces, you can add multiple statements. Example:

() => {
  const str = 'Hello world';
  return str;
}

will do the same as:

function() {
  const str = 'Hello world';
  return str;
}

See the MDN docs for more details.

Some little extra notes:

Because of the syntax rules, when you want to return an object in an arrow function, you'll have to wrap it in braces:

() => ({
  key: 'value',
  another_key: 'another_value'
});

The main differences between function() and () => ... are that arrow functions don't have bindings to some keywords (like this) and that arrow functions don't have a prototype and can't be used as constructors.

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure whether I understand you correctly, but:

const oneLiner = (param) => myArr.filter().map();

const twoLiner = (param) => {func1(); func2();}

If you can put everything in one line (like mapping or filtering) you dont need any parentheses for the body of your function. If you need more than one line, use {}.

Also, the oneLiner returns a value, even without "return". The second function does need the keyword "return" to return something.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.