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:
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:
- We define an arrow function called
myArrowFunction
using theconst
keyword. - The arrow function takes two parameters,
param1
andparam2
. - Inside the function body, it adds
param1
andparam2
and returns the result. - We then call the arrow function by providing values for
param1
andparam2
and store the result in theresult
variable. - Finally, we use
console.log
to print the result to the console, which will display30
sincemyArrowFunction(10, 20)
returns10 + 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