Function Expressions
Lesson 9 of 14 in Coddy's Function Declarations in JavaScript course.
A function expression is a way to create a function without a formal function declaration. It's an anonymous function definition assigned to a variable or used directly within an expression.
Imagine you need a quick tool to complete a small task. Instead of creating a whole named function, you can define a function expression on the fly and assign it to a variable for later use. It's like creating a temporary tool for a specific job.
// Function expression assigned to a variable
const greet = function(name) {
return `Hello, ${name}!`;
};
const message = greet("Alice");
console.log(message); // Output: Hello, Alice!In above example, we define a function expression that takes one argument, name. It's assigned to the variable greet. Notice the function keyword followed by an optional name (can be omitted for anonymous functions) and parentheses.
We call the function using the assigned variable greet with the argument "Alice". The function returns the greeting message for "Alice".
Challenge
EasyYour task is to create a function expression named calculateArea, which calculates the area of a rectangle using a function with two arguments: length and width, and returns the result.
Try it yourself
// Write code here
All lessons in Function Declarations in JavaScript
1Course Introduction
What you will learn?3Ways of Function Declaration
Basic FunctionNested FunctionReturning a FunctionFunction ExpressionsArrow FunctionFunction Constructor