Arrow Functions – Environment Remembering

Arrow functions are mainly intended to resolve several common pain points of traditional Function Expression. it will provide Lexical this binding and Short hand notations with ‘=>’ arrow symbol.
Definition (ECMA6 Standard): Arrow functions bind this lexically, bind return in the Block body case so it returns from the immediately enclosing arrow function.
Syntax: ArrowParameters [no LineTerminator here] => ConciseBody
[table class=”table table-striped”]
Arrow Function Syntax,Arrow Function Examples
(parameters) -> expression,”(x,y) => x * y”
(parameters) -> statement,() => console.log(“Hello JS”);
(parameters) -> { statements },(s) => { n = s.length(); return n;}
[/table]
Simply: which provide a shorter notation of anonymous functions + which binds only lexical this, no dynamic this
Pros: 

  • Much easier for the compiler to optimize, because it doesn’t need to worry about variables escaping from their lexical context, and so doesn’t need to go for chaining lookup.
  • Scope safety, Compactness, and Readability
  • An arrow function expression has a shorter syntax compared to function expressions
    Lexically binds the this value
  • Arrow functions are always anonymous
  • Arrow functions cannot be used as constructors.
  • Arrow functions never have an arguments objects
  • “=>” has only lexical this, no dynamic this

Cons: Not fit when a dynamic context is required like defining methods and get the target from this when handling events.
Lexical (Static) VS Dynamic Scope:
Lexical: Creates a new copy of variable names and values, organized in a hierarchy called “the environment”.
Dynamic: All variable names and their values live in one global table.
Common mistakes of using Arrow Functions:

  • new (() => {}) throws TypeError: (intermediate value) is not a constructor
  • a = (() => {});a.arguments;
    Throws TypeError: ‘caller’ and ‘arguments’ are restricted function properties and cannot be accessed in this context.

JSA