JavaScript Functions

A function in JavaScript is a reusable block of code that performs a specific task or set of instructions. Functions help organize code, reduce redundancy, and enable reusability. Instead of writing the same logic multiple times, you define a function once and invoke it wherever needed, simplifying your program.

Key Features of Functions

  • Reusability: Functions can be called multiple times, avoiding repetition of code.

  • Modularity: Functions break a large task into smaller, manageable pieces, making code easier to understand.

  • Encapsulation: They encapsulate logic, making it isolated and preventing conflicts with other parts of the program.

  • Parameters and Arguments: Functions can take parameters (inputs) that allow them to handle different data dynamically.

  • Return Values: Functions can return values to the calling code, allowing results to be stored or processed further.


Function Declaration

A function declaration defines a named function. To declare a function, use the function keyword, followed by the name of the function, parentheses (), and a block of code {}.

function hellofunc() {
console.log(“Hello, world!”);
}

 

 

Calling a Function

To execute a function, you need to call it by its name followed by parentheses.

hellofunc();
// Output: Hello, world!

 

 

Function Parameters

Functions can accept inputs called parameters. Parameters are specified within the parentheses in the function declaration.

function hellofunc(name) {

  console.log(“Hello, ” + name + “!”);

}

hellofunc(“Alice”);
// Output: Hello, Alice!

hellofunc(“Bob”);
// Output: Hello, Bob! 

 

Return Statement

The return statement stops the execution of a function and returns a value from that function.

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

 let sum = add(5, 3);

console.log(sum);
// Output: 8

 

 

Function Scope

Variables declared within a function are local to that function and cannot be accessed from outside the function.

function testScope() {

  let localVar = “I am local!”;

  console.log(localVar);
// Output: I’m local!

}

 

testScope();

console.log(localVar);
// Error: localVar is not defined

 

 

Default Parameters

You can set default values for function parameters.

function hellofunc(name = “stranger”) {

  console.log(“Hello, ” + name + “!”);

}

hellofunc();
// Output: Hello, stranger!

hellofunc(“Eve”);
// Output: Hello, Eve! 


Types of JavaScript Functions

1. Recursive Functions

A recursive function is a function that calls itself during its execution. This technique can be useful for solving problems that can be broken down into smaller, similar problems.

How to Write a Recursive Function
When writing a recursive function, it’s important to define:

1. Base Case: The condition under which the function stops calling itself to prevent infinite recursion.

2. Recursive Case: The part of the function where it calls itself with modified arguments, moving towards the base case.

Example: Factorial
The factorial of a non-negative integer nnn (denoted as n!n!n!) is the product of all positive integers less than or equal to nnn. Factorial can be defined recursively as:

Base Case: N = 0 or N = 1, then factorial(N) = 1.
Recurrence Relation: N > 1, then factorial(N) = N * factorial(N – 1).

Factorial Function

function factorial(n) {

  // Base case: if n is 0, return 1
      if (n === 0) {
        return 1;
      }

  // Recursive case: n * factorial(n – 1)
  return (n * factorial(n – 1));

}

 console.log(factorial(5));
// Output: 120 

 

2. Function Expression

A function expression in JavaScript defines a function as part of an expression, typically by assigning it to a variable or passing it as an argument. Unlike function declarations, function expressions are not hoisted in the same way, so they cannot be used before they are defined. They can be anonymous, meaning they do not have a name, which is useful for short, one-time operations or callbacks. Function expressions provide flexibility, allowing functions to be treated as values, stored in variables, or passed around like data, making them essential for modern JavaScript patterns and functional programming techniques.

const hellofunc = function(name) {
  console.log(“Hello, ” + name + “!”);
};

hellofunc(“Charlie”);
// Output: Hello, Charlie!

 

 

3. Arrow Functions

Arrow functions in JavaScript offer a concise way to write function expressions using the ‘=>’ syntax. They reduce boilerplate code, making functions shorter and more readable, especially for simple operations. Arrow functions are always anonymous, meaning they do not have a name and are typically assigned to variables or used as callbacks. They are commonly used in modern JavaScript, particularly with array methods like `map()` and `filter()`. Additionally, arrow functions do not have their own ‘this’ context; instead, they inherit ‘this’ from their surrounding scope, which makes them useful in certain scenarios like event handling and class methods.

const hellofunc = (name) => {

  console.log(“Hello, ” + name + “!”);

};

hellofunc(“Dave”);
// Output: Hello, Dave!


If the function has a single parameter, you can omit the parentheses:

const hellofunc = name => {

  console.log(“Hello, ” + name + “!”);

};


For a single-line function, you can omit the curly braces and the return keyword:

const add = (a, b) => a + b;

let sum = add(4, 6);

console.log(sum);
// Output: 10

 

 4. Rest Parameters

The rest parameter syntax in JavaScript allows a function to accept a variable number of arguments and collect them into a single array. It is defined using three dots (‘…’) before the parameter name. This makes it easier to handle multiple inputs without explicitly defining each argument. Unlike the older ‘arguments’ object, rest parameters provide a real array, enabling the use of array methods like ‘map()’, ‘filter()’, and ‘reduce()’. It improves code readability and flexibility, especially when working with functions that need to process an unknown or dynamic number of values in modern JavaScript applications.

 

function sum(…numbers) {

return numbers.reduce((total, num) => total + num, 0);

}

console.log(sum(1, 2, 3));
// Output: 6

console.log(sum(4, 5, 6, 7));
// Output: 22 

 

5. Callback Functions

A callback function in JavaScript is simply a function that you pass into another function so it can be used later. It helps make your code more flexible and interactive. Callbacks are commonly used for things like handling button clicks, waiting for data from an API, or running code after a delay. They allow tasks to happen in the right order without blocking the program. In simple terms, callbacks help JavaScript respond to events and handle actions that don’t happen instantly, making your applications more dynamic and user-friendly.

function processUserInput(callback) {

  let name = prompt(“Please enter your name:”);

  callback(name);

}

 

function helloFunc(name) {

  console.log(“Hello, ” + name + “!”);

}

 

processUserInput(helloFunc); 

 

6. Anonymous Functions

Anonymous functions are functions in JavaScript that do not have a name. Instead of being declared with a specific identifier, they are usually assigned to variables or passed directly as arguments to other functions. This makes them especially useful for short, one-time tasks where creating a named function is unnecessary. Anonymous functions are commonly used in callbacks, event handlers, and array methods like ‘map()’ or ‘forEach()’. They help make code more concise and flexible by allowing functions to be defined exactly where they are needed, improving readability and reducing the need for extra function declarations in simple operations.

setTimeout(function() {

  console.log(“This message is delayed by 2 seconds.”);
}, 2000);

 

 

7. IIFE (Immediately Invoked Function Expression)

An IIFE (Immediately Invoked Function Expression) is a function in JavaScript that runs right after you create it. Instead of defining a function and calling it later, you execute it immediately. It’s often used when you want to run some code just once and keep variables private. This helps avoid cluttering the global scope and prevents naming conflicts. You can think of it as a quick, self-running function that handles setup tasks or small pieces of logic. It’s a simple way to keep your code clean, organized, and limited to where it’s actually needed.

(function() {
  console.log(“This IIFE runs immediately!”);
})();

 

 

8. Higher-Order Functions

A higher-order function is simply a function that works with other functions. It can take a function as input or even return a new function. This makes your code more flexible and reusable. Instead of repeating the same logic, you can pass different functions to handle different tasks. You’ll often see higher-order functions used with things like array methods (‘map’, ‘filter’) or event handling. In simple terms, they help you write cleaner and smarter code by letting functions work together, just like building blocks that can be combined in different ways.

function repeat(operation, num) {
for (let i = 0; i < num; i++) {
operation();
}
}

repeat(() => console.log(“Hello!”), 3);

Output:
Hello!
Hello!
Hello!

 

 9. Closures

A closure is a function defined inside another function that can access variables from its outer function. While this definition seems simple, the real power of closures comes from how scope works in JavaScript. The inner function, known as the closure, can access variables declared within its own scope, variables from its parent function’s scope, and even global variables. However, the outer function cannot access variables defined inside the inner function, as those remain private to the inner scope. This behavior is based on lexical scoping and is what makes closures so powerful.

function outerFunction(outerVariable) {

  return function innerFunction(innerVariable) {
    console.log(“Outer Variable: ” + outerVariable);
    console.log(“Inner Variable: ” + innerVariable);
  };

}

const newFunction = outerFunction(“outside”);

newFunction(“inside”);Output

Outer Variable: outside
Inner Variable: inside

Scroll to Top