What is this ES6 syntax/style of function declaration called?

I tried looking at MDN on arrow functions, that links to an article ES6 In Depth: Arrow functions and the ECMAScript grammar. I didn’t find an example of this style of function body.

See takeStockForBowl in example code below.

Question, what would this style of function definition be called?

Maybe it’s a repurposing of a more basic Javascript syntax and I just don’t see it. Apologies if it’s obvious.

// burrito-bowls-restaurant.js

const supplies = new class {
  _numStock = { protein: 50, grain: 50, veg: 50, }

  take = (item, numItem) => {
    const numStock = this._numStock[item]
    if (!numStock || 0 > numStock - numItem) {
      throw new Error(`shortfall in '${item}'`)
    }
    this._numStock[item] -= numItem
  }
}

const takeForBowl = (item, bowl) => supplies.take(item, bowl[item]?.length)

const takeStockForBowl = bowl => ( // open paren
  takeForBowl('protein', bowl),    // side effect 1
  takeForBowl('grain', bowl),      // side effect 2
  takeForBowl('veg', bowl),        // ...
  bowl.supplied = true,            // side effect n
  bowl                             // result
)                                  // close paren

const bowl_1 = {
  protein: ['mystery biomass'], grain: ['rye'], veg: ['pickle'],
  supplied: false,
}

const bowl_2 = takeStockForBowl(bowl_1)

console.log(bowl_2, supplies._numStock)

>Solution :

First of all, takeStockForBowl is really hard to read.

To understand what’s happening here, we need to understand two things:

Basically what the author has done here is avoided writing the following:

  • Explicit return statement
  • Curly braces for the function body

by taking advantage (or abusing) of implicit return in arrow function and the comma operator.

What comma operator does is it evaluates each of its operands from left to right and returns the value of the last operand which in this case is bowl.

More readable version of this function is:

const takeStockForBowl = bowl => {
  takeForBowl('protein', bowl);
  takeForBowl('grain', bowl);
  takeForBowl('veg', bowl);
  
  bowl.supplied = true;
  
  return bowl;                
}

Leave a Reply