Skip to content

Arrow function JavaScript | Basic code

  • by

JavaScript Arrow Function is a function but it’s a way to create functions in a cleaner way compared to regular functions. Here is a shorter function syntax:

let myFunction = (a, b) => a * b;
let myFunction = (arg1, arg2, ...argN) => {
    statement(s)
}

You can say arrow function expression is a compact alternative to a traditional function expression, but is limited and can’t be used in all situations.

An arrow function in JavaScript is a concise way of writing a function expression. It was introduced in ES6 (ECMAScript 2015) as an alternative to traditional function expressions. Arrow functions have a more compact syntax and provide implicit binding of the this keyword.

Arrow function JavaScript

Simple example code of Arrow Function with No Argument.

<!DOCTYPE html>
<html>
<body>

  <script>
    hello = () => {
      console.log ("Hello Arrow Function!");
    } 
    hello();
  </script>

</body>
</html> 

Output:

Arrow function JavaScript

Arrow Function with Argument

Multipication of 2 number.

   let x = function(x, y) {
     return x * y;
   }
   console.log(x(2,5))

Output: 10

Multiline Arrow Functions

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

let re s= sum(5,7);
console.log(res);

Output: 12

Differences between arrow functions and traditional functions

  • It doesn’t have its own bindings to this or super, and should not be used as methods.
  • It doesn’t have access to the new.target keyword.
  • It isn’t suitable for call, apply and bind methods, which generally rely on establishing a scope.
  • It can’t be used as constructors.
  • It can’t use yield, within its body.
Traditional FunctionArrow Function
Uses the function keyword to define the functionUses a => arrow to define the function
Can have any number of parameters, which are listed in parentheses after the function nameCan have any number of parameters, which are listed in parentheses before the => arrow
Requires a return statement to return a valueReturns the result of the expression without requiring a return statement (if the function body contains only one expression)
Uses its own this keyword, which can be bound to the function’s execution context using bind(), call(), or apply()Uses the this value of the enclosing lexical scope
Can be defined using a function declaration, function expression, or method definitionCan be defined using an arrow function expression or as a concise method definition in an object literal

Comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *