Arrow Functions
Arrow functions in Node.js are a concise way to write functions. They are great for short, single-expression functions and have unique behaviors like lexical this binding. However, they lack their own this, arguments object, and can't be used as constructors with new.
1. Basic Syntax
const add = (a, b) => a + b;
2. Single Parameter
const greet = name => `Hello, ${name}`;
No need for parentheses if there’s only one parameter.
3. No Parameters
const sayHello = () => 'Hello!';
Use empty parentheses when there are no parameters.
4. Implicit Return
const double = x => x * 2;
No need for return or curly braces for single expression functions.
5. Block Body
const sum = (a, b) => {
const result = a + b;
return result;
};
Use curly braces when you need multiple statements.
6. Lexical this
const obj = {
name: 'Node.js',
getName: () => this.name
};
console.log(obj.getName()); // Outputs: undefined (depends on surrounding scope)
Arrow functions don’t have their own this; they inherit this from the surrounding context.
7. No arguments
Object
const add = () => {
console.log(arguments); // `arguments` is not defined
};
Arrow functions don’t have their own arguments object.
8. No new
Keyword
const Person = (name) => {
this.name = name;
};
const john = new Person('John'); // Error: Person is not a constructor
Arrow functions can’t be used as constructors.
9. No Prototype
const ArrowFunc = () => {};
console.log(ArrowFunc.prototype); // Outputs: undefined
Arrow functions don’t have a prototype property, so they can’t be used to define methods on a prototype.
10. Arrow Functions in Callbacks
setTimeout(() => console.log('Executed after 1 second'), 1000);
Often used in callbacks for their concise syntax and lexical this binding, especially in asynchronous operations.
11. Empty Arrow Function
// An empty arrow function returns undefined
const empty = () => {};
(() => "foobar")();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)
12. Promise
promise
.then((a) => {
// …
})
.then((b) => {
// …
});
You Might Also Like
Toggle Classes Based on Conditions
Use classList.toggle to add or remove classes based on a condition. ``` const button = document.get...
Functions : Declaration, Expression, IIFE, Callback and More
### 1. Function Declaration ``` function greet(name) { return `Hello, ${name}!`; } ``` ### 2. F...