Beginner25 min read

Functions

Learn to define and call functions, understand parameters and return values, and explore function expressions.

Function Declarations

A function is a reusable block of code designed to perform a particular task. You define it once and can call it as many times as you need.

The most common way to create a function is with a function declaration:

javascript
function greet(name) {
  console.log('Hello, ' + name + '!');
}

greet('Alice'); // Hello, Alice!
greet('Bob');   // Hello, Bob!

Here are the key parts:

  • function keyword — tells JavaScript you are defining a function.
  • Name — follows the same rules as variable names. By convention, function names use camelCase: calculateTotal, getUserName, isValid.
  • Parameters — the variables listed inside the parentheses. They act as placeholders for the values you will pass in when calling the function. You can have zero, one, or many parameters separated by commas.
  • Arguments — the actual values you pass when calling the function. In greet('Alice'), the string 'Alice' is the argument that gets assigned to the name parameter.
  • Function body — the code inside the curly braces {} that runs each time the function is called.

An important feature of function declarations is hoisting. JavaScript moves function declarations to the top of their scope before executing any code. This means you can call a function before it appears in your source code:

javascript
sayHello(); // This works!

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

You can define functions with multiple parameters:

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

add(3, 5); // 8

If you call a function with fewer arguments than parameters, the missing ones will be undefined. You can also set default parameter values:

javascript
function greet(name = 'World') {
  console.log('Hello, ' + name + '!');
}

greet();        // Hello, World!
greet('Alice'); // Hello, Alice!

Return Values

Functions can send a value back to the code that called them using the return statement:

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

const sum = add(3, 5);
console.log(sum); // 8

The return statement does two things:

  1. Sends a value back to where the function was called.
  2. Stops the function immediately. Any code after return in the same block will not execute.
javascript
function checkAge(age) {
  if (age < 0) {
    return 'Invalid age'; // Early return — exits here
  }
  return 'Age is ' + age;
}

This pattern of early returns is very common. It lets you handle edge cases at the top of a function and keep the main logic unindented.

If a function has no return statement, or uses return without a value, it returns undefined:

javascript
function sayHi() {
  console.log('Hi!');
  // no return statement
}

const result = sayHi(); // logs 'Hi!'
console.log(result);    // undefined

Because functions return values, you can use them directly in expressions:

javascript
function double(n) {
  return n * 2;
}

const total = double(5) + double(10); // 10 + 20 = 30
console.log(double(double(3)));       // double(6) = 12

This composability is one of the most powerful aspects of functions — you can combine them, nest them, and build complex logic from simple building blocks.

Function Expressions

Instead of using a function declaration, you can create a function and assign it to a variable. This is called a function expression:

javascript
const greet = function(name) {
  return 'Hello, ' + name + '!';
};

console.log(greet('Alice')); // Hello, Alice!

The function on the right side of the = is called an anonymous function because it has no name. The variable greet holds a reference to the function, and you call it using the variable name.

You can also give function expressions a name, creating a named function expression:

javascript
const factorial = function fact(n) {
  if (n <= 1) return 1;
  return n * fact(n - 1); // name 'fact' is accessible inside
};

The name fact is only accessible inside the function itself, which is useful for recursion and debugging (the name appears in stack traces).

Key difference from declarations: function expressions are not hoisted. You cannot call them before the line where they are defined:

javascript
greet('Alice'); // Error! greet is not defined yet

const greet = function(name) {
  return 'Hello, ' + name;
};

When to use each:

  • Use function declarations for top-level functions that form the main structure of your code. Hoisting makes them available everywhere in the scope, which can improve readability.
  • Use function expressions when you need to pass a function as a value — for example, as a callback to another function, or when you want to conditionally assign different functions to the same variable.

Both approaches are valid and widely used. As you progress, you will also learn about arrow functions (=>), which are a more concise syntax for function expressions.

Functions in Action

html
<h2 id="output">Results</h2>
<ul id="results"></ul>

<script>
  // Function declaration
  function multiply(a, b) {
    return a * b;
  }

  // Function expression
  const formatResult = function(label, value) {
    return label + ': ' + value;
  };

  // Using return values
  const product = multiply(6, 7);
  const message = formatResult('6 x 7', product);

  // Display on the page
  const list = document.getElementById('results');

  const items = [
    formatResult('3 + 5', multiply(1, 3) + multiply(1, 5)),
    formatResult('6 x 7', multiply(6, 7)),
    formatResult('10 x 10', multiply(10, 10)),
  ];

  items.forEach(function(item) {
    const li = document.createElement('li');
    li.textContent = item;
    list.appendChild(li);
  });
</script>

What does a function return if there is no return statement?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.