Functions: Reusable Code

JavaScript ECMAScript 2024 · ✓ verified by execution on

Building Blocks of JavaScript

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value. However, for a procedure to truly qualify as a function, it should take some input and return an output where there is an obvious relationship between the two. Think of a function as a mini-program within your main program: it has its own logic, it does a specific job, and it saves you from copying and pasting the exact same logic over and over again.

To use a function, you must define it somewhere in the scope from which you wish to call it. The scope determines where variables and functions are visible and accessible.

Function Declarations

A function definition (also called a function declaration) consists of the function keyword, followed by the name of the function, a list of parameters enclosed in parentheses (), and the body enclosed in curly braces {}.

The code inside the curly braces is not executed immediately when the function is declared. Instead, JavaScript simply registers the function in memory. The code only actually runs when the function is explicitly invoked (called).

javascript
function greet() {
  console.log('Hello');
}
greet();
Output
Hello

Parameters and Arguments

Functions become truly powerful when they accept inputs, known as parameters. By accepting parameters, a function becomes a flexible template rather than a rigid set of commands. When you call a function, you pass concrete values called arguments that are bound to these parameters during that specific execution.

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

function printDouble(n) {
  console.log(n * 2);
}
printDouble(5);
Output
10

Pass-by-Value

Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the calling function.

This happens because JavaScript creates a separate copy of the primitive value (like a number or string) and assigns it to the local parameter variable. The original variable outside the function remains entirely untouched. This design prevents functions from accidentally destroying your data, making your code much more predictable.

javascript
function modify(x) {
  x = 10;
}
let y = 5;
modify(y);
console.log(y);
Output
5

Edge Cases: Missing and Extra Arguments

Unlike stricter languages (like Java or C++), JavaScript is very forgiving when it comes to arguments. If you don’t pass enough arguments to match the defined parameters, JavaScript doesn’t crash or throw an error. Instead, the missing ones simply default to the value undefined.

javascript
function sayHi(name) {
  console.log('Hi, ' + name);
}
sayHi();
Output
Hi, undefined

If you pass too many arguments, the extra ones are simply ignored by the named parameters. (They are still technically accessible via a hidden object called arguments, but they won’t map to any named parameter).

javascript
function noArgs() {
  console.log('Called');
}
noArgs(1, 2, 3);
Output
Called

Hoisting

One interesting feature of JavaScript function declarations is that they can be hoisted. This means the function declaration can appear below the call in the code, but it still executes correctly.

JavaScript scans your entire file and lifts (“hoists”) all function declarations to the top of their enclosing scope before it runs any code. This allows you to organize your files by putting your main logic at the top and tucking the helper functions safely at the bottom.

javascript
hoisted();
function hoisted() {
  console.log('I am hoisted!');
}
Output
I am hoisted!

The Function Machine

Here is a visual representation of how a function receives inputs and produces a result.

Argument Argument Function Internal Logic Return
A function as a machine: arguments go in, the body runs its internal logic, and a single return value comes back out.

Visualizing Execution

Let’s visualize how parameter binding and hoisting work together using an interactive tracer.

javascript · visualize
function multiply(a, b) {
  let result = a * b;
  console.log(result);
}

let first = 3;
let second = 4;
multiply(first, second);

Check yourself

If you call a function with fewer arguments than there are parameters, what value is assigned to the missing parameters?

Reveal answer

undefined — Missing arguments are assigned the value `undefined` in JavaScript.

Which of the following statements about JavaScript function parameters is true?

Reveal answer

They are passed by value — Parameters are essentially passed to functions by value. Re-assigning a parameter inside the function doesn't change the original variable.

What is 'hoisting' in the context of function declarations?

Reveal answer

The function declaration is moved to the top of its scope, allowing it to be called before it appears in the code. — Function declarations can be hoisted, meaning they appear below the call in the code but still work.

What happens if you pass more arguments than a function has parameters?

Reveal answer

The extra arguments are ignored by the function parameters. — Extra arguments are ignored by the named parameters (though they can still be accessed via the `arguments` object).

Challenges

Challenge 1 +15 XP

Write a function named `sayWelcome` that prints 'Welcome' to the console. We will call it for you.

javascript
  • Test 1 — expects "Welcome\n"
Need a hint? (−25% XP)

Use the `function` keyword, followed by the name `sayWelcome`, parentheses `()`, and curly braces `{}`.

Show solution (0 XP)
function sayWelcome() {
  console.log('Welcome');
}

// Do not modify below
sayWelcome();

Challenge 2 +20 XP

Write a function named `printDouble` that takes one parameter `n` and prints `n * 2` to the console. We will call it for you.

javascript
  • Test 1 — expects "10\n"
Need a hint? (−25% XP)

Put `n` inside the parentheses of your function declaration.

Show solution (0 XP)
function printDouble(n) {
  console.log(n * 2);
}

// Do not modify below
printDouble(5);