top of page
Writer's pictureThe Tech Platform

Arrow Functions in JavaScript



ES6 Arrow functions provide you with an alternative way to write a shorter syntax compared to the function expression.


The following are a few facts about arrow functions:

  • Using the arrow function, curly braces, parenthesis, function, and return keywords become optional.

  • The arrow function has a lexical scoping to this context.

One of the main differences between arrow functions and regular functions is that arrow functions can only be anonymous. They are not bound to any identifier.


Thus they created dynamically. We cannot name an arrow function as we do for the regular functions. However, if you’d like to call or reuse an arrow function, you will need to assign it to a variable.


Limitations:

  • Does not have its own bindings to this or super, and should not be used as methods.

  • Does not have new.target keyword.

  • Not suitable for call, apply and bind methods, which generally rely on establishing a scope.

  • Can not be used as constructors.

  • Can not use yield, within its body.


Basic syntax

One param. With simple expression return is not needed:

param => expression 

Multiple params require parentheses. With simple expression return is not needed:

(param1, paramN) => expression 

Multiline statements require body braces and return:

param => 
{
    let a = 1;
    return a + param;
}

Multiple params require parentheses. Multiline statements require body braces and return:

(param1, paramN) => 
{
    let a = 1;
    return a + param1 + paramN;
}


Code:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrow Function</h2>

<p id="demo"></p>

<script>
var hello;

hello = () => {
  return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>

Output:




The Tech Platform

Recent Posts

See All

Comments


bottom of page