DEV Community

Jaisurya
Jaisurya

Posted on

Functions in JavaScript

A function is a reusable, self-contained block of code designed to perform a specific task. Instead of writing the same logic multiple times throughout a program, you define it once inside a function and run or call it whenever needed.

Think of a function like a kitchen blender: you put ingredients in (inputs), it performs a specific operation (processing) and it produces a smoothie (output).

Core components of a function:

Name: A descriptive identifier used to call the function (e.g., calculate_num or send_email).

Parameters(Inputs): Variables declared in the function definition that accept values (known as arguments) passed into it.

Body: The block of code that executes when the function is invoked.

Return value(Output): The final result the function sends back to the part of the program that called it.

// 1. Define the function
function calculateTotal(price, taxRate) {
  const tax = price * taxRate;
  const total = price + tax;
  return total;
}

// 2. Call the function with different values
const shirtTotal = calculateTotal(25, 0.08); // 8% tax on a $25 shirt
console.log(shirtTotal); // Output: 27

const shoesTotal = calculateTotal(80, 0.08); // 8% tax on $80 shoes
console.log(shoesTotal); // Output: 86.4
Enter fullscreen mode Exit fullscreen mode

Top comments (0)