Function Expressions

Grade 6, page 6 of 11. A one-minute read.

Here's a mind-bending idea: in JavaScript, a function is a value, just like a number or a string. That means you can store a function in a variable:

JavaScript
const square = function (number) {
  return number * number;
};

console.log(square(5));
console.log(square(12));

It prints

25
144

This is called a function expression. The function itself has no name (it's anonymous), but it's stored in a variable called square, so you call it using that name.

It works just like a normal function declaration, with one important difference. You can call a function declaration before it appears in your code, because JavaScript reads all the declarations first. But a function expression stored in const can only be used after the line where it's created:

JavaScript
console.log(cube(3));

function cube(n) {
  return n * n * n;
}

It prints

27
JavaScript
console.log(half(10));

const half = function (n) {
  return n / 2;
};

It stops with an error

Uncaught ReferenceError: Cannot access 'half' before initialization

(The reason for this is called hoisting, and we'll dig into it properly in Grade 9. For now, just create your functions before you use them, and you'll never have a problem.)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning