Functions

by REPLY2SAGAR

JavaScript

//function taking parameters and returning value
function add(a, b) {
    return a + b;
}

let sum = add(5, 3);
console.log(sum);  // Output: 8


//Anonymous function
let show = function(message) {
    console.log(message);
};

show("I am an anonymous function");

//Arrow function
const multiply = (a, b) => a * b;

let product = multiply(4, 3);
console.log(product);  // Output: 12

//IIFE - Immedietly invoked function expression
(function() {
    console.log("This runs right away");
})();

//function with default parameters
function greet(name = "Guest") {
    console.log("Hello, " + name + "!");
}

greet("Alice");  // Output: Hello, Alice!
greet();         // Output: Hello, Guest!

//function with rest parameters
function sumAll(...numbers) {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sumAll(1, 2, 3, 4, 5));  // Output: 15

//callback function
function processUserInput(callback) {
    let name = "sagar";
    callback(name);
}

processUserInput(name => {
    console.log('Hello ' + name);
});