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 (1)

Collapse
 
will_laurenson_c16056cd19 profile image
Will Laurenson

A function is useful because it lets you keep a piece of logic in one place and reuse it with different inputs. In the example, calculateTotal() takes price and taxRate as parameters, calculates the tax, and returns the final amount.

For example:

const shirtTotal = calculateTotal(25, 0.08);
Enter fullscreen mode Exit fullscreen mode

Here, 25 and 0.08 are the arguments passed to the function. The function then returns 27, which is stored in shirtTotal.

One important benefit is that if the calculation needs to change later, you only need to update the function once rather than changing the same logic throughout the program.