FAQ: Functions - Concise Body Arrow Functions

Arrow function syntax affords demarcated blocks so long as return is present, meaning no implicit return when braces or multi-line code is used. It is just a simple refinement of the normal function expression.

const foo = function (n) {
  return n;
};

becomes,

const foo = n => {
  return n;
};

Concise body functions are the ones that take full advantage of the relaxed syntax of arrow functions. They are a special use case for arrow functions, especially when used in higher-order functions as callbacks. They also help us code with more expressions and pure functions.

const foo = n => n;
const bar = (f, n) => f(n);
console.log(bar(foo, 42))    //  42

Or,

const foo = n => n * 6;
const bar = (f, n) => f(n);
console.log(bar(foo, 7))    //  42

I thought I understood functions well, until I tried to run this bit of code (or the concise version of it):

const sumNumbers = number => {
     const sum = number + number;
     return sum;
};

console.log (sumNumbers(2,3));

So the result is 4 instead of 5, as the number 2 is added to itself

My question is:
Isn’t this function supposed to look like like this instead?

const sumNumbers = (number1, number2) => {

  const sum = number1 + number2;

  return sum; 
}

console.log(sumNumbers(2,3))
 //Produces 5 this time

Nobody mentions this in the discussion above, like the code is just fine. Am I missing something? :'D

Not insofar as you show a grasp of basic functions, no. The concept of concise body is something else to grapple with.

const addAB = (a, b) => a + b;

Their real beauty shines when we reach the concept of higher-order functions, which will come up eventually. Be patient.

Are you familiar with Python or Ruby lambdas? These are very similar in nature. They are functional expressions that can be used within other expressions.

1 Like

Thank you for your answer, it just threw me. I thought maybe I’d missed something important!
JS is my first language so every concept is new, I can’t link them to parallels in my head yet. :v But as always, your explanation is super helpful, thank you so much!

1 Like