Engineering note · Node.js

Functions : Declaration, Expression, IIFE, Callback and More

Functions are fundamental building blocks in Node.js, used to organize code and handle logic.

By Published

Node.js

1. Function Declaration

CODE SAMPLE Code snippet
function greet(name) {
    return `Hello, ${name}!`;
}

2. Function Expression

CODE SAMPLE Code snippet
const greet = function(name) {
    return `Hello, ${name}!`;
};

3. Arrow Function

CODE SAMPLE Code snippet
const greet = (name) => `Hello, ${name}!`;

4. Immediately Invoked Function Expression (IIFE)

CODE SAMPLE Code snippet
(function() {
    console.log('IIFE runs immediately!');
})();

5. Callback Functions

Functions passed as arguments.

CODE SAMPLE Code snippet
function fetchData(callback) {
    // Simulate async operation
    setTimeout(() => {
        callback('Data received');
    }, 1000);
}

fetchData((data) => console.log(data));

6. Anonymous Functions

Functions without a name, often used as callbacks.

CODE SAMPLE Code snippet
setTimeout(function() {
    console.log('Anonymous function');
}, 1000);

7. Rest Parameters

Collects all remaining arguments into an array.

CODE SAMPLE Code snippet
function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

8. Default Parameters

Setting default values for function parameters.

CODE SAMPLE Code snippet
function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

9. Higher-Order Functions

Functions that accept or return other functions.

CODE SAMPLE Code snippet
function createMultiplier(multiplier) {
    return (x) => x * multiplier;
}
const double = createMultiplier(2);

10. Async/Await

CODE SAMPLE Code snippet
async function fetchData() {
    const data = await fetch('url');
    console.log(data);
}

More engineering notes

Toggle Classes Based on Conditions

Use classList.toggle to add or remove classes based on a condition. ``` const button = document.get...

Scope

Scope in Node.js defines where variables and functions can be accessed in your code. It includes glo...