Skip to content

How to call arrow function in JavaScript | Code

  • by

There’s no difference between calling a regular function and an arrow function in JavaScript.

// Function in JavaScript
function regular(){
  console.log("regular function");
}
regular(); //regular function

// Arrow Function
const arrow = () => console.log("Arrow function");
arrow(); //Arrow function

Simple Arrow function

let greet = () => console.log('Hello');
greet(); // Hello

Arrow Function with Argument

let greet = x => console.log(x);
greet('Hello'); // Hello 

Call arrow function in JavaScript

A simple example code defines an arrow function to greet a person. This code showed how to call an arrow function.

<!DOCTYPE html>
<html>
<body>
  <script>
    const greet = (name) => {
      return `Hello, ${name}!`;
    };
    
    console.log(greet('Stevn king'));

  </script>
</body>
</html> 

Output:

How to call arrow function in JavaScript

In JavaScript, you can define and call an arrow function like this:

// Define an arrow function
const myArrowFunction = (param1, param2) => {
  // Function body
  return param1 + param2;
};

// Call the arrow function
const result = myArrowFunction(10, 20);

console.log(result); // Output will be 30

In the example above:

  1. We define an arrow function called myArrowFunction using the const keyword.
  2. The arrow function takes two parameters, param1 and param2.
  3. Inside the function body, it adds param1 and param2 and returns the result.
  4. We then call the arrow function by providing values for param1 and param2 and store the result in the result variable.
  5. Finally, we use console.log to print the result to the console, which will display 30 since myArrowFunction(10, 20) returns 10 + 20.

Arrow functions are a concise way to write functions in JavaScript, especially when the function’s body consists of a single expression. They also have lexical scoping for this, which makes them useful in certain situations.

Do comment if you have any doubts or suggestions on this JS arrow function.

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 *