J

JavaScript Handbook

Clean • Professional

Function Definitions in JavaScript

2 minute

Function Definitions in JavaScript

In JavaScript, a function definition is a way to create a reusable block of code that performs a specific task. Functions help organize your code, reduce repetition, and make programs more modular and maintainable.

A function can:

  • Accept input values called parameters
  • Perform operations or logic on these inputs
  • Optionally return a value for use elsewhere in the program

Why Functions Are Important

  1. Reusability – Write once, use multiple times.
  2. Modularity – Break complex problems into smaller, manageable pieces.
  3. Maintainability – Easier to update, debug, and extend.
  4. Flexibility – Functions can be passed as arguments, returned from other functions, and used in advanced patterns like closures and callbacks.

Types of Function Definitions

JavaScript supports several ways to define functions, each with unique behavior:

learn code with durgesh images

1. Function Declarations

A function declaration defines a named function using the function keyword. It is hoisted, meaning it can be called anywhere in its scope, even before its definition in the code.

Syntax:

function functionName(parameters) {
  // function body
  return value; // optional
}

Example:

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

// Calling the function
greet("Alice"); // Output: Hello, Alice!

Can have default parameters in modern JavaScript:

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

2. Function Expressions (Named and Anonymous)

Function expressions define a function as part of a variable assignment. They are not hoisted, so they must be defined before being called.

Syntax:

// Anonymous Function Expression
const variableName = function(parameters) {
  // Code block
  return value; // Optional
};

// Named Function Expression
const variableName = function functionName(parameters) {
  // Code block
  return value; // Optional
};

a. Anonymous Function Expression

No name assigned to the function.

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

greet("Bob"); // Output: Hello, Bob!

b. Named Function Expression

Function has a name, useful for recursion or debugging.

const factorial = function fact(n) {
  return n <= 1 ? 1 : n * fact(n - 1);
};

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

3. Immediately Invoked Function Expressions (IIFE)

An IIFE is a function that is executed immediately after its definition. Often used to create a private scope and avoid polluting the global namespace.

Syntax:

(function() {
  // function body
})();

or using arrow functions:

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

Example:

(function() {
  const message = "Hello from IIFE!";
  console.log(message);
})();
// Output: Hello from IIFE!

 

Article 0 of 0