Arrow Function and "this" keyword

shubhamb

Shubham_Baghel

Posted on March 9, 2020

Arrow Function and "this" keyword

Arrow Function

Arrow function expression are a more concise syntax for writing function expressions although without its own bindings to the this, arguments, super, or new.target keywords. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.

Code samples:

//ES5 example for function var multiplyFunction = function(x, y) { return x * y; }; // ES6 arrow function much concise syntax const multiplyArrowfunction = (x, y) => { return x * y };

Following are the examples about arrow function
Examples:

let sumofNumber = (a, b) => a + b; /* This arrow function is a shorter form of: let sumofNumber = function(a, b) { return a + b; }; */ alert( sumofNumber (1, 2) ); // 3

In case if you have one argument only,then parentheses around parameters can be avoided,making that even shorter ans simpler syntactically.

let multiplybytwo = n => n * 2; // roughly the same as: let multiplybytwo = function(n) { return n * 2 } alert( multiplybytwo (3) ); // 6

this keyword

Execution context for an execution is global — which means if a code is being executed as part of a simple function call, then this refers to a global object.
Arrow functions do not bind their own this, instead, they inherit the one from the parent scope, which is called "lexical scoping".In code with multiple nested functions, it can be difficult to keep track of and remember to bind the correct this context. In ES5, you can use workarounds like the .bind method.Because arrow functions allow you to retain the scope of the caller inside the function, you don’t need to use bind.

function printWindow () { console.log("Simple function call") console.log(this === window); } printWindow(); //prints true on console console.log(this === window) //Prints true on console.
💖 💪 🙅 🚩
shubhamb
Shubham_Baghel

Posted on March 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related