Understanding JavaScript Functions

Explore how JavaScript functions work, with beginner-friendly explanations of their uses and behavior.

🎯 Introduction

Learn how to create, call, and execute JavaScript functions, and understand function scope, closures, and argument passing. These concepts help you write concise, efficient code, avoid common pitfalls, and improve your front-end development skills.


🔍 What Is a Function? Starting with the Basics

A JavaScript function is a reusable block of code. It breaks a complex task into smaller pieces that are easier to call and manage. Like a recipe that a cook follows to prepare a dish, a function defines the steps for completing a task.

There are three common ways to create functions:

// Function declaration
function greet(name) {
    return 'Hello, ' + name + '!';
}

// Function expression
const greet2 = function (name) {
    return 'Hello, ' + name + '!';
};

// Arrow function (ES6; not the focus of this article)
const greet3 = name => 'Hello, ' + name + '!';
Start with function declarations and function expressions. You can explore arrow functions in more detail later.

🧩 Calling Functions and Returning Values

Calling a function executes its code. For example:

console.log(greet('Alex'));

This prints “Hello, Alex!” A return statement ends function execution and sends a result back to the caller. If no value is returned, the result is undefined.

Functions can also take no arguments:

function sayHi() {
    console.log('Hi!');
}
sayHi();

🧠 Scope and Function Scope

Scope determines where a variable is accessible. JavaScript functions have their own scope: local variables defined inside a function cannot be accessed from outside it.

function foo() {
    let message = 'Hello';
    console.log(message);
}
foo();
console.log(message); // Error: message is not defined

Each function call has its own scope. Its local variables do not overwrite variables outside that scope, and external code cannot access them directly.

Understanding function scope helps prevent variable name conflicts, especially in larger projects.

🔄 Parameters and Arguments: Values or References?

Two important cases arise when passing arguments to JavaScript functions:

  • Primitive arguments (such as numbers, strings, and booleans) are passed by value. Reassigning a parameter does not change the original variable.
  • Object arguments (such as objects and arrays) pass a reference value. Modifying the referenced object inside the function affects the same object outside it.

For example:

function changeNumber(num) {
    num = 100;
}
let a = 50;
changeNumber(a);
console.log(a); // 50; the external variable is unchanged

function changeObj(obj) {
    obj.name = 'Alex';
}
let person = { name: 'Sam' };
changeObj(person);
console.log(person.name); // Alex

🔒 Closures: Functions That Remember

Closures are one of JavaScript’s most powerful features. A function can retain access to variables from the scope in which it was created, even after the outer function has finished executing.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        console.log('Count:', count);
    };
}

const counter = outer();
counter(); // Count: 1
counter(); // Count: 2

Here, inner accesses the count variable in outer. That variable remains available through the closure.

Closures are useful for counters and caching data.


📝 Function Declarations vs. Function Expressions

These forms look similar, but hoisting is an important difference.

Function declarations are made available before execution reaches their declaration, so you can call them earlier in the scope.

sayHello();

function sayHello() {
    console.log('Hello');
}

A function expression must be evaluated before you can call the assigned function. Calling it earlier, as below, causes an error.

sayHi(); // Error

const sayHi = function () {
    console.log('Hi');
};

💡 Tip: Providing Default Parameter Values Manually

When an argument is omitted, its parameter has the value undefined. You can check for this inside the function and supply a default:

function greet(name) {
    if (typeof name === 'undefined') {
        name = 'friend';
    }
    return 'Hello, ' + name + '!';
}

❓ Knowledge Check

Q1: How do function expressions and function declarations differ? Function declarations are hoisted and can be called before their declaration. A function expression must be evaluated and assigned before the function can be called.

Q2: What is a closure, and what is it used for? A closure lets a function retain access to variables from its defining scope. It can access and update an outer function’s local variables and is often used for caching and private state.


🧪 Exercises

Exercise 1: Write a function that accepts two arguments and returns their product. Call it and print the result.

function multiply(a, b) {
    // Implement the function here
}

console.log(multiply(3, 5)); // Expected output: 15

Exercise 2: Use a closure to create a counter that increments by 1 on each call and returns the current count.

function createCounter() {
    // Return an inner function that implements the counter
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2

🎉 You now understand function declarations, calls, scope, argument passing, and closures in JavaScript. Keep building on these foundations as you learn front-end development!