Chapter 10 of 31

JavaScript Functions

As our programs become bigger, writing everything in one long block of code quickly becomes messy. Imagine having the same piece of code that calculates a total in ten different places. If something needs to change, you'd have to update it everywhere.

Functions solve this problem.

A function lets us group a piece of code into a reusable block that we can run whenever we need it.

What is a Function?

A function is a reusable block of code designed to perform a specific task.

For example:

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

We've created a function called greet.

But notice that nothing has been printed yet. Defining a function doesn't execute it.

We need to call it:

greet();

Output:

Hello, World!

So the basic idea is:

Create function → Call function → Code runs

Creating a Function

The basic syntax is:

function functionName() {
    // code to execute
}

For example:

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

Here:

  • function is the keyword used to create a function.

  • sayHello is the function's name.

  • () contains parameters, if any.

  • {} contains the code that belongs to the function.

To execute it:

sayHello();

Why Do We Use Functions?

Functions are useful because they make code:

  • Reusable — write code once and use it multiple times.

  • Organized — divide a large program into smaller pieces.

  • Easier to understand — each function can handle one specific task.

  • Easier to maintain — changes can be made in one place.

For example, instead of writing:

console.log("Welcome, John!");
console.log("Welcome, Alex!");
console.log("Welcome, Sarah!");

we can create one reusable function.


Function Parameters

Sometimes a function needs some information to do its job. We can pass that information using parameters.

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

Here, name is a parameter.

Now we can call the function with different values:

greet("John");
greet("Alex");
greet("Sarah");

Output:

Hello, John
Hello, Alex
Hello, Sarah

This is one of the biggest advantages of functions: the same code can work with different data.


Parameters vs Arguments

These two terms can be confusing at first.

Consider:

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

greet("John");

Here:

  • name is the parameter.

  • "John" is the argument.

A simple way to remember:

Parameter → Variable defined by the function.
Argument → Actual value passed when calling the function.


Multiple Parameters

A function can have multiple parameters.

function add(a, b) {
    console.log(a + b);
}

add(10, 5);

Output:

15

Here, a receives 10 and b receives 5.

We can call the same function again with different values:

add(20, 30);
add(100, 50);

Output:

50
150

Returning a Value

Sometimes we don't want a function to simply print something. We want it to calculate something and give the result back.

For this, we use the return statement.

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

let result = add(10, 5);

console.log(result);

Output:

15

Here, return sends the result back to where the function was called.

We can then use that result in other operations:

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

let total = add(10, 5);

console.log(total * 2);

Output:

30

return Stops the Function

When JavaScript reaches a return statement, the function immediately stops executing.

function test() {
    console.log("First");

    return;

    console.log("Second");
}

test();

Output:

First

The "Second" message never runs because the function has already returned.


Default Parameters

We can give a parameter a default value.

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

greet("John");
greet();

Output:

Hello, John
Hello, Guest

When we provide a value, JavaScript uses that value. When we don't, it uses the default.


Function Expressions

Functions can also be stored inside variables.

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

greet();

Here, the function is assigned to the greet variable.

This is called a function expression.

You'll see this style frequently in JavaScript, especially when working with callbacks and other functions.


Arrow Functions

Modern JavaScript provides a shorter way to write functions called arrow functions.

Instead of:

const add = function(a, b) {
    return a + b;
};

we can write:

const add = (a, b) => {
    return a + b;
};

For a simple function that directly returns an expression, we can make it even shorter:

const add = (a, b) => a + b;

Then:

console.log(add(10, 5));

Output:

15

Arrow functions are very common in modern JavaScript, and we'll use them a lot when working with arrays and other advanced concepts.


Local Variables Inside Functions

Variables created inside a function are generally available only inside that function.

function showMessage() {
    let message = "Hello";

    console.log(message);
}

showMessage();

This works because message exists inside the function.

But this won't work:

function showMessage() {
    let message = "Hello";
}

console.log(message); // ❌ Error

This concept is related to scope, which we'll cover separately.


A Practical Example

Let's create a function to calculate the final price of a product after adding tax:

function calculateTotal(price, tax) {
    return price + (price * tax / 100);
}

let total = calculateTotal(1000, 18);

console.log(total);

Output:

1180

Instead of writing the calculation every time, we created one reusable function.

We can now use it for different products:

console.log(calculateTotal(500, 18));
console.log(calculateTotal(2000, 18));
console.log(calculateTotal(750, 18));

That's the real power of functions.


Function Declaration vs Function Expression vs Arrow Function

You'll encounter all three styles:

Type

Example

Function Declaration

function add(a, b) { ... }

Function Expression

const add = function(a, b) { ... }

Arrow Function

const add = (a, b) => a + b

For now, focus mainly on understanding what functions do, how parameters work, and how return works. The differences between these styles become more important as you move into advanced JavaScript.

Conclusion

Functions allow us to write code once and reuse it whenever we need it. They are one of the most important concepts in JavaScript and are used practically everywhere.

The basic pattern is:

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

let result = add(10, 5);

Remember the key ideas:

  • Function → Reusable block of code.

  • Parameter → Input defined by the function.

  • Argument → Value passed to the function.

  • return → Sends a value back from the function.

  • Arrow function → Shorter modern function syntax.

Once functions are clear, the next important concept is Scope, which explains where variables and functions can be accessed in your JavaScript program.