Arrow Functions
Arrow Functions
ARROW FUNCTIONS
By
G.Sowmya
Assistant Professor
CSE-AIML Dept
MLR Institute of Technology
Overview of the Presentation
1. Implicit Return
If the function body consists of only a single expression, the result is returned
automatically.
const square = num => num * num;
console.log(square(4)); // Output: 16
Arrow Functions
2. No this Binding
Unlike regular functions, arrow functions do not have their own this. Instead,
they inherit this from their surrounding scope (lexical scoping).
const obj = {
value: 10,
regularFunction: function() {
setTimeout(function() {
console.log(this.value); // `this` refers to the global object, NOT `obj`
}, 1000);
},
Arrow Functions
arrowFunction: function() {
setTimeout(() => {
console.log(this.value); // `this` refers to `obj`
}, 1000);
}
};
obj.regularFunction(); // Output: undefined (or error in strict mode)
obj.arrowFunction(); // Output: 10
Arrow Functions
4. No arguments Object
Arrow functions do not have their own arguments object. If needed, use rest
parameters (...args) instead.
const sum = (...args) => args.reduce((acc, val) => acc + val, 0);
console.log(sum(1, 2, 3, 4)); // Output: 10
Arrow Functions
Example programs:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrow Function Example</title>
</head>
<body>
<h2>Arrow Function Example: Double a Number</h2>
Arrow Functions
Thank You