Functions in JavaScript

Functions in JavaScript

Functions are the building blocks of any JavaScript program. They allow you to encapsulate reusable pieces of logic, making your code modular and easier to understand. In this blog, we’ll explore what functions are, how they work, and the different ways you can define and use them in JavaScript.


What Is a Function?

A function is a block of code designed to perform a specific task. Functions are executed when they are invoked or "called."

Syntax of a Function

function functionName(parameters) {
    // Code to execute
    return value; // Optional
}

Types of Functions

JavaScript offers several ways to define functions, giving you flexibility based on your use case.


1. Function Declaration

A function declaration defines a named function that can be called anywhere in your code.

function greet(name) {
    return `Hello, ${name}!`;
}
 
console.log(greet("Alice")); // Output: Hello, Alice!

2. Function Expression

A function expression assigns a function to a variable. This type of function is not hoisted, meaning you cannot call it before defining it.

const add = function (a, b) {
    return a + b;
};
 
console.log(add(2, 3)); // Output: 5

3. Arrow Function

Arrow functions provide a concise syntax and are particularly useful for callbacks and one-liners.

const multiply = (a, b) => a * b;
 
console.log(multiply(4, 5)); // Output: 20

4. Immediately Invoked Function Expression (IIFE)

An IIFE is a function that runs as soon as it’s defined.

(function () {
    console.log("IIFE executed!");
})();

5. Anonymous Function

An anonymous function has no name and is often used in situations like event handlers or callbacks.

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

Parameters and Arguments

Functions can accept parameters, which act as placeholders for values, and arguments, which are the actual values passed to the function.

Example with Default Parameters

function sayHello(name = "Guest") {
    return `Hello, ${name}!`;
}
 
console.log(sayHello("Bob"));  // Output: Hello, Bob!
console.log(sayHello());       // Output: Hello, Guest!

Return Statement

The return statement specifies the value a function should output. If no return is provided, the function returns undefined.

function square(num) {
    return num * num;
}
 
console.log(square(4)); // Output: 16

Higher-Order Functions

Functions in JavaScript can accept other functions as arguments or return them as results. These are known as higher-order functions.

Example: Passing a Function as an Argument

function operate(a, b, operation) {
    return operation(a, b);
}
 
const sum = (a, b) => a + b;
console.log(operate(5, 3, sum)); // Output: 8

Callback Functions

A callback function is a function passed as an argument to another function and executed later.

Example: Using a Callback with forEach

const numbers = [1, 2, 3, 4];
numbers.forEach((num) => console.log(num * 2)); // Output: 2, 4, 6, 8

Closures

A closure is a function that remembers the variables from its outer scope, even after the outer function has finished executing.

Example of a Closure

function outerFunction(outerVariable) {
    return function innerFunction(innerVariable) {
        console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
    };
}
 
const newFunction = outerFunction("Outside");
newFunction("Inside"); // Output: Outer: Outside, Inner: Inside

Practice Code Snippet

JavaScript Code Runner on: functions

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.