In JavaScript, an arrow function is a concise way of writing a function expression. It was introduced in ES6 and provides a shorter syntax compared to traditional function expressions. Arrow functions are often used for creating anonymous functions or for defining functions with a shorter and more readable syntax. Here's an example of an arrow function and its equivalent traditional function expression:
// Arrow function syntax: (parameters) => { function body }
// Example 1: A simple arrow function that adds two numbers
const add = (a, b) => {
return a + b;
};
// Example 2: Arrow function with implicit return (for one-liner functions)
const square = (num) => num * num;
// Example 3: Arrow function with no parameters
const sayHello = () => {
console.log("Hello!");
};
// Example 4: Arrow function as a callback
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16]
Equivalent Traditional Function Expression:
// Traditional function expression syntax: function(parameters) { function body }
// Example 1: Equivalent traditional function for adding two numbers
const add = function(a, b) {
return a + b;
};
// Example 2: Equivalent traditional function with explicit return (for one-liner functions)
const square = function(num) {
return num * num;
};
// Example 3: Equivalent traditional function with no parameters
const sayHello = function() {
console.log("Hello!");
};
// Example 4: Equivalent traditional function as a callback
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map(function(num) {
return num * num;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16]
Comments