Javascript · Functions (Advanced)
Function Expressions
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — A Function Stored in a Variable
So far you've declared functions with `function name() {}`. There's a second way: create the function without a name and store it in a variable. This is called a function expression:
const cheer = function () {
console.log("Go Aquachu!");
};
cheer();
The variable `cheer` now holds the function, and you call it exactly like before, with parentheses. Note the semicolon at the end: it's an assignment like any other.
Why bother?
Right now this may look like a longer way to do the same thing, and that's fair. The real payoff comes when you start passing functions around, especially with the array methods of class 12. For now, just get comfortable with the form.
Exercise 2 — Declaration vs Expression
// Declaration
function heal(amount) {
return amount * 2;
}
// Expression
const heal = function (amount) {
return amount * 2;
};
Both create a function called with `heal(20)`. Parameters and `return` work the same way. The differences are in the form: the expression has no name after `function`, is assigned with `=`, and ends with `;`.
const heal = function (amount) {
return amount * 2;
};
console.log(heal(20));
console.log(heal(5) + heal(5));
Exercise 3 — Spot the Expression
Which line is a function expression?
Options
• ```const attack = function () { };```
• ```function attack() { }```
• ```attack();```
• ```const attack = 20;```
Hint : An expression stores a nameless function in a variable.
Exercise 4 — Store the Roar
Write `roar` as a function expression, then call it.
const roar ____ ____ () {
console.log("ROAR!");
};
____();
Options: = function roar : roar() =>
Hint : An assignment, then the keyword that creates a function, then a normal call.
Exercise 5 — No Hoisting This Time
Remember: a declaration can be called before it's written, because JavaScript reads declarations first. A function expression is a variable, and a `const` doesn't exist before its line:
// cheer(); // Uncomment this line to see the error!
const cheer = function () {
console.log("Go Zap!");
};
cheer();
With expressions, the order matters: define first, call after. That's one reason many people like them, the code reads top to bottom.
Exercise 6 — Quiz: Called Too Early
What happens when this code runs?
greet();
const greet = function () {
console.log("Hi!");
};
Options
• An error: greet isn't available yet
• ```Hi!```
• Nothing
• ```undefined```
Hint : Ask yourself whether a const variable exists before its line.
Exercise 7 — Naming the Variable
The function itself has no name, but the variable does. Use the same naming habits as before: camelCase, starting with a verb. And prefer `const`, so the variable can't be accidentally replaced by something else.
const computeDamage = function (base, level) {
return base + level * 2;
};
const isCritical = function (roll) {
return roll >= 9;
};
console.log(computeDamage(20, 5));
console.log(isCritical(10));
Which one should I use?
Both are correct and common. In this course, declarations stay the default for standalone functions. Expressions matter because they lead to the next chapters: arrow functions and functions passed around as values.
Exercise 8 — Damage Expression
Complete the function expression so that `double(15)` returns 30.
const double = ____ (value) {
____ value * 2;
};
console.log(double(15));
Options: function return const console.log =>
Hint : Creating the function and sending the result back each use a specific keyword.
Exercise 9 — Two Ways to Create a Function
Match each element with its description.
Items to match
• function f() { }
• const f = function () { };
• Calling a declaration before its line
• Calling an expression before its line
Definitions
• A declaration
• A function expression
• Works: declarations are read first
• Error: the variable doesn't exist yet
Exercise 10 — Rewrite as Expressions
Two functions are declared with the classic syntax. Rewrite them as function expressions stored in constants with the same names, keeping the same behaviour.
Step 1: `describe(name, level)` returns `"name (level X)"`, for example `describe("Zap", 3)` returns `"Zap (level 3)"`.
Step 2: `announce(text)` prints the text between `">> "` and `" <<"`.
Step 3: use them together to produce the expected output.
>> Zap (level 3) <<
>> Metachu (level 12) <<
Starter code
// Rewrite these two as function expressions
function describe(name, level) {
return name + " (level " + level + ")";
}
function announce(text) {
console.log(">> " + text + " <<");
}
// Use them here
Back to the course