CodeToLive

Functions in JavaScript

Functions in JavaScript are reusable blocks of code that perform a specific task. They can take parameters and return values. Functions are fundamental to writing clean, modular, and reusable code.

Defining a Function

Functions in JavaScript are defined using the function keyword or as arrow functions.


// Function Declaration
function greet(name) {
    console.log(`Hello, ${name}!`);
}

greet("Alice");

// Arrow Function
const greetArrow = (name) => {
    console.log(`Hello, ${name}!`);
};

greetArrow("Bob");
      

Returning Values

Functions can return values using the return keyword. The returned value can be used in other parts of the program.


function add(a, b) {
    return a + b;
}

let result = add(5, 10);
console.log("Sum:", result);
      

Anonymous Functions

Anonymous functions are functions without a name. They are often used as callbacks or immediately invoked function expressions (IIFE).


setTimeout(function() {
    console.log("This runs after 2 seconds.");
}, 2000);

// IIFE
(function() {
    console.log("This is an immediately invoked function.");
})();
      

Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return functions. Examples include map, filter, and reduce.


const numbers = [1, 2, 3, 4, 5];

// Using map to double each number
const doubled = numbers.map(num => num * 2);
console.log("Doubled:", doubled);

// Using filter to get even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log("Evens:", evens);

// Using reduce to sum all numbers
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("Sum:", sum);
      

Closures

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. Closures are useful for creating private variables.


function createCounter() {
    let count = 0;
    return function() {
        count++;
        return count;
    };
}

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
      

Default Parameters

Default parameters allow you to initialize function parameters with default values if no argument is passed.


function greet(name = "Guest") {
    console.log(`Hello, ${name}!`);
}

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

Rest Parameters

Rest parameters allow you to represent an indefinite number of arguments as an array.


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

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
      
Next: Objects