Sub topic 1
Functions Are Values
Prerequisites
This chapter assumes you know basic JavaScript syntax and can declare variables with var, let, and const. You should also be comfortable calling functions, passing arguments, and working with objects.
Functions Are Values
In JavaScript, a function is a value, just like a number or a string. You can store it in a variable, pass it to another function, or return it from one. Because functions are values, the language offers more than one way to create them. The two oldest forms are declarations and expressions.
Function Declarations
A function declaration is a statement that starts with the function keyword and gives the function a name:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5The declaration creates a binding called add in the surrounding scope.
Function Expressions
A function expression creates a function inside an expression, usually the right-hand side of an assignment. The function itself can be anonymous because the variable supplies a way to call it:
const multiply = function (a, b) {
return a * b;
};
const subtract = (a, b) => a - b;
console.log(multiply(2, 3)); // 6
console.log(subtract(5, 2)); // 3The arrow function subtract is also an expression. Later chapters cover how arrows behave differently.
Hoisting: Calling Before Defining
Hoisting means JavaScript sets up a scope's bindings before it runs any code in that scope. Declarations and expressions are hoisted differently:
| Form | What is hoisted | Calling before the definition |
|---|---|---|
| Function declaration | Name and body | Works |
| Expression assigned to `const`/`let` | Name only, left uninitialized | Throws `ReferenceError` |
| Expression assigned to `var` | Name, set to `undefined` | Throws `TypeError` |
The period between the start of the scope and the let/const line is called the temporal dead zone (TDZ). Any access to the variable during the TDZ throws an error.
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}
try {
multiply(2, 3);
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
const multiply = function (a, b) {
return a * b;
};Exercise
What does this code log, and why? var greet = function () { return 'hi'; }; appears after the line console.log(typeof greet);.
Show answer
It logs "undefined". var hoists the name greet and sets it to undefined, and the function is assigned only when the later line runs. Calling greet() at that point would throw a TypeError.