Function Expressions
In this lesson, you'll learn how to create functions as values and assign them to variables, offering a different approach than function declarations.
What Is a Function Expression?
A function expression is when you create a function and assign it to a variable, just like you'd assign a number or string. Instead of using the function keyword to declare a named function at the top level, you're treating the function itself as a value.
Here's the syntax:
const greet = function() {
return "Hello!";
};
console.log(greet()); // "Hello!"
Notice the function has no name after the function keyword—it's anonymous and stored in the variable greet.
How Function Expressions Differ from Declarations
With a function declaration (what you learned in lesson 379), you write:
function sayHi() {
return "Hi!";
}
With a function expression, you write:
const sayHi = function() {
return "Hi!";
};
The key differences:
- Declarations are hoisted—you can call them before they appear in code
- Expressions are not hoisted—the variable exists, but it's
undefineduntil the assignment runs - Expressions can be anonymous; declarations must have a name
Why Use Function Expressions?
Function expressions shine when you want to:
- Pass functions as values to other functions
- Assign functions conditionally
- Treat functions like any other data
Key Takeaway: Function expressions create functions as values assigned to variables, offering flexibility but without hoisting, unlike function declarations.