arrow function without curly braces

  • Last Update :
  • Techknowledgy :

I'm new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses? For example: One can also use curly braces to prevent a single line arrow function from returning a value -- or to make it obvious to the next developer that a single line arrow function shouldn't, in this case, be returning anything. Actually in a briefcase when somebody uses braces in an arrow function declaration, it is equal to below:

This is our Splunktool team suggestion ✌, we tried and its working fine
const addNums = (numOne, numTwo) => numOne + numTwo;​
const sum = addNums(5, 3); // sum would be 8

Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."

Here are some more examples that all do the same thing:

const a = (who) => "hello " + who + "!";
const b = (who) => ("hello " + who + "!");
const c = (who) => (
   "hello " + who + "!"
);
const d = (who) => (
   "hello " +
   who +
   "!"
);
const e = (who) => {
   return "hello " + who + "!";
};

You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:

const x = () => {} // Does nothing
const y = () => ({}) // returns an object

Suggestion : 2

Without curly braces, you can only put one expression to the right of the arrow =>. Intuitively, this means you can only use the no curly brace syntax for "one-liners". You can use the ternary operator ?, &&, and ||. But you cannot use if statements or semicolons. With curly braces {}. With this syntax, the arrow function does not have an implicit return. 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 you see =>, you're looking at an arrow function. There are two ways to declare an arrow function:

// 'getAnswer()` is an arrow function that returns 42
const getAnswer = () => 42;

getAnswer(); // 42
2._
// 'getAnswer()` is an arrow function that returns 42
const getAnswer = () => {
   return 42;
};

getAnswer(); // 42

Returning an object literal from an arrow function is tricky:

// Syntax error! JavaScript assumes curly braces after `=>` means
// you're using the curly braces syntax
const getObj = () => {
   answer: 42
};

// With parentheses around the object literal, the below function
// correctly returns an object with `obj.answer = 42`
const getObj = () => ({
   answer: 42
});

getObj(); // 42

Like normal functions, arrow functions can take zero or more parameters. You must put the parameter names in parentheses (param1, param2, param3) => {} unless your arrow function takes exactly one parameter.

// If your arrow function takes no params, declare it with
// `() =>`
const getAnswer = () => 42;

// If your arrow function takes 1 param, you can omit the
// parentheses around the parameter names
let noop = v => v;
// Or, equivalently:
noop = (v) => v;

// If your arrow function takes more than 1 param, you must
// put parentheses around the parameter names
const add = (a, b) => a + b;

For example, suppose you try to call setTimeout() in a class method. If you use a normal function as opposed to an arrow function, this will not be an instance of MyClass.

class MyClass {
   constructor(message) {
      this.message = message;
   }

   print() {
      setTimeout(function() {
         // undefined, because `this` is a `Timeout` object in
         // a `setTimeout()` callback
         this.message;
      }, 100);
   }
}

const obj = new MyClass('Hello, World');
obj.message; // 'Hello, World'
obj.print();

Suggestion : 3

The braces can only be omitted if the function directly returns an expression. If the body has additional lines of processing, the braces are required — and so is the return keyword. Arrow functions cannot guess what or when you want to return. An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage: Note: Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.

1._
param => expression

(param) => expression

   (param1, paramN) => expression

param => {
   statements
}

(param1, paramN) => {
   statements
}
2._
(a, b, ...r) => expression
   (a = 400, b = 20, c) => expression([a, b] = [10, 20]) => expression({
      a,
      b
   } = {
      a: 10,
      b: 20
   }) => expression
3._
async param => expression
async (param1, param2, ...paramN) => {
   statements
}
5._
// Traditional anonymous function
(function(a, b) {
   return a + b + 100;
});

// Arrow function
(a, b) => a + b + 100;

const a = 4;
const b = 2;

// Traditional anonymous function (no parameters)
(function() {
   return a + b + 100;
});

// Arrow function (no arguments)
() => a + b + 100;
6._
// Traditional anonymous function
(function(a, b) {
   const chuck = 42;
   return a + b + chuck;
});

// Arrow function
(a, b) => {
   const chuck = 42;
   return a + b + chuck;
};

Suggestion : 4

Arrow functions are handy for simple actions, especially for one-liners. They come in two flavors: With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something. Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result. Parentheses can be omitted, if there’s only a single argument, e.g. n => n*2. For now, we can already use arrow functions for one-line actions and callbacks.

1._
let func = (arg1, arg2, ..., argN) => expression;
2._
let func = function(arg1, arg2, ..., argN) {
   return expression;
};
3._
let sum = (a, b) => a + b;

/* This arrow function is a shorter form of:

let sum = function(a, b) {
  return a + b;
};
*/

alert(sum(1, 2)); // 3
5._
let sayHi = () => alert("Hello!");

sayHi();
6._
let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?
   () => alert('Hello!') :
   () => alert("Greetings!");

welcome();

Suggestion : 5

Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result. With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something. Arrow functions are handy for one-liners. They come in two flavors: Arrow functions explained!

/**
There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions.

It’s called “arrow functions”, because it looks like this:
*/
let func = (arg1, arg2, ...argN) => expression

// Here is non-arrow version of the above function
let func = function(arg1, arg2, ...argN) {
   return expression;
};

let sum = (a, b) => a + b;

/* This arrow function is a shorter form of:

let sum = function(a, b) {
  return a + b;
};
*/
console.log(sum(1, 2)); // 3

let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }

console.log(double(3)); // 6

let sayHi = () => console.log("Hello!");

sayHi();

let sum = (a, b) => { // the curly brace opens a multiline function
   let result = a + b;
   return result; // if we use curly braces, then we need an explicit "return"
};

console.log(sum(1, 2)); // 3

Suggestion : 6

Notice the difference? When you use curly braces {}, you need to explicitly state the return. However, when you don't use curly braces, the return is implied and you don't need it. Remember I mentioned about the different body types - concise body and block body. Just to quickly update you in case you skipped that section (I'm a bit sad, but not offended 😝). Block body is where you use curly braces and have an explicit return. Concise body is where you don't use curly braces, and you skip the return keyword. Alright, now you're caught up, let's get back to the gotcha 🤯 With a normal function, we always had to use parentheses. However, with Arrow Functions, parentheses are optional if there is ONLY one parameter.

1._
// Explicit Return, Multi-Line
a => {
   return a
}

// Explicit Return, Single-Line
a => {
   return a
}

// Implicit Return, Multi-line
a => (
   a
)

// Implicit Return, Single-Line
a => a

// Multiple Parameters, Parentheses Required
(a, b) => a + b
2._
const sayHi = function(name) {
   return name
}
3._
// Multi-line
const sayHi = (name) => {
   return name
}

// Single-line
const sayHi = (name) => {
   return name
}
5._
// Normal Function
const numbers = function(one) {}

// Arrow Function, with parentheses
const numbers = (one) => {}

// Arrow Function, without parentheses
const numbers = one => {}
6._
// Normal Function
const numbers = function(one, two) {}

// Arrow Function, with parentheses
const numbers = (one, two) => {}

Suggestion : 7

Arrow functions have two syntactic forms for their function bodies. They may be defined with a block body (denoted by curly braces) () => { ... } or with a single expression () => ..., whose value is implicitly returned. "never" enforces no braces around the function body (constrains arrow functions to the role of returning an expression) This rule can enforce or disallow the use of braces around arrow function body. "always" enforces braces around the function body

The second one is an object for more fine-grained configuration when the first option is "as-needed". Currently, the only available option is requireReturnForObjectLiteral, a boolean property. It’s false by default. If set to true, it requires braces and an explicit return for object literals.

"arrow-body-style": ["error", "always"]
2._
/*eslint arrow-body-style: ["error", "always"]*/ /*eslint-env es6*/
let foo = () => 0;
3._
let foo = () => {
   return 0;
};
let foo = (retv, name) => {
   retv[name] = true;
   return retv;
};
5._
/*eslint arrow-body-style: ["error", "as-needed"]*/ /*eslint-env es6*/
let foo = () => 0;
let foo = (retv, name) => {
   retv[name] = true;
   return retv;
};
let foo = () => ({
   bar: {
      foo: 1,
      bar: 2,
   }
});
let foo = () => {
   bar();
};
let foo = () => {};
let foo = () => {
   /* do nothing */ };
let foo = () => { // do nothing.};let foo = () => ({ bar: 0 });
6._
/*eslint arrow-body-style: ["error", "as-needed", { "requireReturnForObjectLiteral": true }]*/ /*eslint-env es6*/
let foo = () => ({});
let foo = () => ({
   bar: 0
});