Arrow functions in JavaScript | Lecture 3
Arrow
functions in JavaScript are a concise way to write functions introduced in ES6.
They have a shorter syntax compared to traditional function expressions and do
not bind their own this, making them especially useful
in scenarios where you want to preserve the context of the enclosing function.
Syntax
(parameters) => expression
If the
function has a single parameter, parentheses are optional:
param => expression
For
multiple parameters or a block body, parentheses and curly braces are required:
(param1, param2) => {
//
statements
return
result;
}
Examples
1. Simple Arrow Function
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
2. Single Parameter
const square = x => x * x;
console.log(square(4)); // Output: 16
3. No Parameters
const greet = () => "Hello, world!";
console.log(greet()); // Output: Hello, world!
4. Multiline Block Body
If the
function body has multiple statements, wrap it in curly braces and explicitly
use return when needed:
const multiplyAndLog = (a, b) => {
const
result = a * b;
console.log(`Result: ${result}`);
return
result;
};
multiplyAndLog(3, 4); // Output: Result: 12
5. Using Arrow Functions in Array Methods
Arrow
functions are commonly used with array methods like map, filter, and reduce.
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map(num => num *
num);
console.log(squaredNumbers); // Output: [1, 4, 9,
16]
6. Arrow Functions and this
Arrow
functions do not have their own this and
instead inherit this from the enclosing lexical
context.
function Person() {
this.age
= 0;
setInterval(() => {
this.age++; // `this` refers to the Person object
console.log(this.age);
}, 1000);
}
const person = new Person();
7. Returning an Object
To return
an object literal, wrap it in parentheses:
const createPerson = (name, age) => ({ name, age
});
console.log(createPerson("Alice", 30));
// Output: { name: 'Alice', age: 30 }
8. Default Parameters
Arrow
functions can use default parameter values:
const greet = (name = "Guest") =>
`Hello, ${name}!`;
console.log(greet()); // Output: Hello, Guest!
console.log(greet("John")); // Output:
Hello, John!
Key Differences from Regular Functions
- No Own this: Arrow functions inherit this from the surrounding scope.
- Cannot Use as Constructors: Arrow functions cannot be
used with new.
- No arguments Object: Arrow functions do not
have an arguments object. Use rest parameters
instead.
Example:
const sum = (...args) => args.reduce((acc, num)
=> acc + num, 0);
console.log(sum(1, 2, 3)); // Output: 6
Comments
Post a Comment