Menu
Coddy logo textTech

Function Expression

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 49 of 77.

In JavaScript, a function expression is a way to define a function as part of an expression. Unlike function declarations, function expressions are not hoisted, which means they cannot be called before they are defined in the code.

Here's the basic syntax of a function expression:

let functionName = function(parameters) {
	// Code to be executed
	// ...
	return value; // Optional return statement
};

The function keyword is followed by an optional name for the function. If a name is provided, it becomes a named function expression; otherwise, it's an anonymous function expression. The parameters are specified in parentheses, and the function body is enclosed in curly braces.

Here's an example of a named function expression:

let add = function sum(a, b) {
	return a + b;
};

console.log(add(3, 5)); // Output: 8

In this example, add is the variable that holds the function, and sum is the optional name of the function. Even though the function has a name, you cannot call sum directly; you must use the variable add.

Here's an example of an anonymous function expression:

let multiply = function(a, b) {
	return a * b;
};

console.log(multiply(4, 2)); // Output: 8

In this case, the function does not have a name, and it's directly assigned to the variable multiply.

Function expressions are often used when you want to pass a function as an argument to another function, or when you want to create a function on the fly.

challenge icon

Challenge

Easy

Create a function expression named calculateArea that takes two arguments, width and height, and returns the area of a rectangle. The function should be assigned to a variable named calculateArea.

For example:

console.log(calculateArea(5, 10)); // Output: 50
console.log(calculateArea(3, 7));  // Output: 21

Cheat sheet

Function expressions define functions as part of an expression and are not hoisted (cannot be called before definition).

Basic syntax:

let functionName = function(parameters) {
	// Code to be executed
	return value; // Optional
};

Named function expression:

let add = function sum(a, b) {
	return a + b;
};

console.log(add(3, 5)); // Output: 8

Anonymous function expression:

let multiply = function(a, b) {
	return a * b;
};

console.log(multiply(4, 2)); // Output: 8

Function expressions are useful for passing functions as arguments or creating functions dynamically.

Try it yourself

// Type your code below


// Don't change the lines below
console.log(calculateArea(5, 10));
console.log(calculateArea(3, 7));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals