Function expressions
Learn the anonymous function expression assigned to a variable.
Function expressions
In JavaScript, functions are values, so you can assign them to a variable. This is called a function expression. The definition starts with the function keyword but does not need a name.
Example: const add = function(a, b) { return a + b; };. Here the unnamed function is assigned to add. It is also called an anonymous function. You call it the same way: add(3, 5).
const for functions
Using const in a function expression is a common choice; it prevents reassignment. Example: const greet = function(name) { console.log("Hi " + name); };.
Here greet is a constant variable, but the function inside can still be called: greet("Alex"). You can also use let, but const is safer because it blocks accidental reassignment.
Exercise Constant function expression
Assign a function expression to a variable called square. The function should take an n parameter and return n * n. Then print the result with console.log(square(6)).
Show example solution
const square = function(n) {
return n * n;
};
console.log(square(6));
Test yourself
-
Which of these is a function expression?
- function greet() { }
- greet() { }
- const greet = ();
- const greet = function() { };
Show answer
const greet = function() { }; — Correct. Assigning a function to a variable is a function expression.
-
Complete the function expression
const multiply = ____(a, b) { return a * b; }; console.log(multiply(3, 4));Show answer
const multiply = function(a, b) { return a * b; }; console.log(multiply(3, 4)); -
Match each form to its name
- function greet() { }
- Function declaration
- const greet = function() { };
- Function expression
- greet()
- Function call
- function() { }
- Anonymous function