0

I've seen this type of JavaScript code (contrived):

 const a = "hello"
 const b = () => ({a})

Is this just shorthand for this equivalent fat arrow function:

const b = () => { return {a} }

Or does it have some other purpose? And what do you call these?

It seems a lot to add a construct just to save one reserved word.

HankCa
  • 9,129
  • 8
  • 62
  • 83
  • Yes, they're equivalent. If an array function doesn't begin with `{`, it's just a shortcut that returns the expression. – Barmar Jan 18 '20 at 01:41
  • I don't think there's a specific name for arrow functions that are just a single expression. – Barmar Jan 18 '20 at 01:43
  • The extra `()` around the `{a}` are necessary to tell it that `{` does not start a block. – Thilo Jan 18 '20 at 01:44
  • 1
    [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body) calls the two forms of arrow functions *concise body* and *block body*. – Barmar Jan 18 '20 at 01:45
  • 2
    Why do you call this an identity function? It does not return its input. Or anything related to its input. – Thilo Jan 18 '20 at 01:45
  • 2
    It's not an identity function, it's a *constant* function (which always returns the same value). – Bergi Jan 18 '20 at 02:04

1 Answers1

0

I think you are asking about the right side of an arrow function.

It is just more concise, with the special rule that if the right side is a single expression to be returned, it doesn't have to be { return expr }, but just expr.

const sq = (x => x * x);
const hyphenAround = (s => `-${s}-`);
[1, 3, 5].map(a => a * a)
[1, 3, 5].reduce((a, b) => a + b)

const sq = (x => x * x);
const hyphenAround = (s => `-${s}-`);

console.log(sq(3));
console.log(hyphenAround("hello"));
console.log([1, 3, 5].map(a => a * a));
console.log([1, 3, 5].reduce((a, b) => a + b));

In your example, it is

const a = "hello"
const b = () => ({a})

which is the same as

const a = "hello"
const b = () => ({a: a})

Those are called shorthand property names.

let a = "hello"
const b = () => ({
  a
});

console.log(b());

a = "a long sentence";
console.log(b());

x = 123;
y = "hello"
z = [1, 3, 5];

console.log({
  x,
  y,
  z
});
nonopolarity
  • 146,324
  • 131
  • 460
  • 740