Arrow functions

JavaScript uses almost all variations of arrows. With ES6, it introduces a new syntax for writing functions. We have always written function expressions in JavaScript. It is idiomatic to write code like this in JavaScript (this example is in jQuery):

    $("#submit-btn").click(function (event) { 
      validateForm(); 
      submitMessage(); 
    }); 

This is a typical jQuery event handler. The event handler click() function accepts a function as a parameter and we will simply create an inline anonymous function expression and pass it to the click function. This style of writing anonymous function expressions is known as Lambda functions. Several other languages support this feature. Though lambdas are more or less standard in new languages, JavaScript was responsible for popularizing their usage. However, the lambda syntax in JavaScript has not been very concise. ES6 arrow functions fill that gap and provide a concise syntax to write functions.

Arrow function provide a more concise syntax than the traditional function expressions; for example, consider the following piece of code:

    const num = [1,2,3] 
    const squares = num.map(function(n){ 
      return n*n; 
    }); 
    console.log(squares); //[1,4,9] 

Arrow functions syntax can simplify the function to the following line of code:

    const squares_6 =num.map( n=> n*n) 

As you can see, there is no function or return keyword anywhere. If your function has only one argument, you will end up writing the function as identifer => expression.

When you need multiple arguments, you need to wrap the argument list in braces:

  • No parameters: () => {...}
  • One parameter: a => {...}
  • More than one parameters: (a,b) => {...}

Arrow functions can have both the statement block bodies as well as expression bodies:

    n => { return n+n}  //statement block 
    n =>n+n            //expression 

Both are equivalent but the second variation is concise and preferred. Arrow functions are always anonymous. One important aspect of arrow functions that we will discuss a little later is that arrow functions do not bind their own values of the this keyword-the value is lexically derived from the surrounding scope. As we have not yet looked at the this keyword in detail, we will defer the discussion to a later part of this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.178