Josh Writes

Small boy with big dreams.

Understanding Functions in JavaScript

Imagine you need to add two numbers multiple times in your code. You could write the same addition statement over and over, but that’s inefficient. Instead, you can use a function—a reusable block of code that performs a specific task whenever called.

Why Use Functions?

A key principle in programming is DRY (Don’t Repeat Yourself). Functions help avoid repetition, keep your code organized, and make it easier to modify later.

For example, instead of writing this every time:

let sum1 = 5 + 3;
let sum2 = 10 + 7;
let sum3 = 20 + 4;

You can create a function:

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

console.log(addNumbers(5, 3));  // Output: 8
console.log(addNumbers(10, 7)); // Output: 17
console.log(addNumbers(20, 4)); // Output: 24

Now, whenever you need to add two numbers, you reuse the function instead of rewriting the logic.

Declaring a Function

A function in JavaScript is created using the function keyword, followed by:

  • A name (to describe its purpose)
  • Parentheses () (to hold optional parameters)
  • Curly braces {} (to contain the code that runs)

Example:

function greet() {
    console.log("Hello! Welcome.");
}

Calling a Function

To execute a function, you call (invoke) it using its name followed by parentheses:

greet(); // Output: Hello! Welcome.

Using Parameters and Arguments

Functions become more useful when they accept values (parameters).

For example, instead of always greeting with “Hello!”, we can personalize the message:

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

greetPerson("Alice"); // Output: Hello, Alice!
greetPerson("Bob");   // Output: Hello, Bob!

  • name is a parameter—a placeholder in the function definition.
  • “Alice” and “Bob” are arguments—the actual values passed when calling the function.

Returning Values from Functions

Instead of just printing results, functions can return values for later use.

Let’s say we want to calculate the price after tax:

function calculateTotal(price, taxRate) {
    return price + (price * taxRate);
}

let totalPrice = calculateTotal(100, 0.08);
console.log("Total Price: $" + totalPrice); // Output: Total Price: $108

Here, calculateTotal() computes the total, and we store the result in a variable for future use.

Functions with Loops

Functions can also work with loops, making repetitive tasks easier.

For example, if we need to print numbers from 1 to 5, we can write:

function printNumbers() {
    for (let i = 1; i <= 5; i++) {
        console.log(i);
    }
}

printNumbers();

Output:

1
2
3
4
5

Instead of writing multiple console.log() statements, we use a loop inside a function for efficiency.

Using Default Parameters

What if a user forgets to provide an argument? We can set a default value:

function greetUser(name = "Guest") {
    console.log("Welcome, " + name + "!");
}

greetUser(); // Output: Welcome, Guest!
greetUser("Sophie"); // Output: Welcome, Sophie!

Arrow Functions (A Shorter Way)

A more modern way to write functions is with arrow functions (ES6):

const multiply = (x, y) => x * y;

console.log(multiply(4, 3)); // Output: 12

This is just a shorter version of:

function multiply(x, y) {
    return x * y;
}

Conclusion

Functions make JavaScript programming simpler, reusable, and more efficient. Whether you’re performing calculations, printing messages, or looping through numbers, functions help you write clean, organized code that’s easy to maintain.

Thanks for reading this blog, check out more of our blogs in our home page!