Hemanth's Scribes
python

Arrow Functions in Javascript

Author Photo

Hemanth HM

· 2 min read · .md

CoffeeScript is influencing javascript with fat arrows! As python had influenced it before with list comprehensions.

Well, the grammer looks like : ~~~ AssignmentExpression :

ArrowFunctionExpression
...

ArrowFunctionExpression :

ArrowFormalParameters => [lookahead ∉ { "{" }] AssignmentExpression
ArrowFormalParameters => Block

ArrowFormalParameters :

( FormalParameterList_opt )
Identifier

**Grammer in simple English :**

  * => works as a function keyword.

  * (Parameters) are placed before the =>.

  * {} are needed for the function body if there are more than one line or else it's optional.

  * For one liners an explicit return is not needed, for others it's needed.

Some examples from the proposal :

// Empty arrow function returns undefined let empty = () => {};

// Single parameter case needs no parentheses around parameter list let identity = x => x;

// No need for parentheses even for lower-precedence expression body let square = x => x * x;

// Parenthesize the body to return an object literal expression let key_maker = val => ({key: val});

// Statement body needs braces, must use 'return' explicitly if not void let odds = evens.map(v => v + 1);

let fives = []; nats.forEach(v => { if (v % 5 === 0) fives.push(v); });

// ''=>'' has only lexical ''this'', no dynamic ''this'' const obj = { method: function () {
    
    
    return () => this;
    

} }; assert(obj.method()() === obj);

let fake = {steal: obj.method()}; assert(fake.steal() === obj);

// But ''function'' still has dynamic ''this'' of course let real = {borrow: obj.method}; assert(real.borrow()() === real);

Do [read](https://mail.mozilla.org/pipermail/es-discuss/2012-March/thread.html#21800) arrow function syntax simplified on the ES discussion list!

Making is more easier :

var sum = function(a,b){return a+b;} 

Can be re-written with fat arrows as :

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

Ok, it's time for me to let sleep = dream => 'zzz' + 'zzzz...'; ;) [ Yes dream is lost! ]
#python#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.

100%