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:
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:
console.log(cube(3));
function cube(n) {
return n * n * n;
}
It prints
27
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.)