Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;                
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading