Functions

What is a Function in JavaScript?

  • A function is a reusable block of code designed to perform a particular task. It runs when it is called or invoked.
  • Reusable Block: Code is written once and can be used (or called) multiple times without rewriting.

Why use Functions?

  • Reusability: Code once, use multiple times.
  • Modularity: Break program into smaller blocks.
  • Readability: Clean and understandable code.
  • Maintainability: Easy to fix and update logic.

How to Create a Function

function functionName(parameters) {
    // code to be executed
}

Example:

function greet(name) {
    console.log("Hello, " + name + "!");
}

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