0
0
JavascriptConceptBeginner · 3 min read

What is Function Expression in JavaScript: Simple Explanation

A function expression in JavaScript is when you create a function and assign it to a variable. Unlike function declarations, function expressions are not hoisted and can be anonymous, meaning they don't need a name.
⚙️

How It Works

Think of a function expression like writing a recipe and putting it inside a labeled jar (a variable). You can then use the jar's label to follow the recipe whenever you want. This means the function is stored as a value inside the variable.

Unlike a function declaration, which is like a recipe posted on the kitchen wall and ready to use anytime, a function expression only exists after the line where you assign it. So, you can't use it before that point.

This allows you to create functions dynamically and pass them around like any other value, making your code flexible and powerful.

💻

Example

This example shows a function expression assigned to a variable and then called to print a greeting.

javascript
const greet = function(name) {
  return `Hello, ${name}!`;
};

console.log(greet('Alice'));
Output
Hello, Alice!
🎯

When to Use

Use function expressions when you want to create functions dynamically or pass them as values to other functions. They are useful for callbacks, event handlers, or when you want to keep functions private inside another function.

For example, when you want to run some code after a button click, you can pass a function expression as the click handler. Also, function expressions help in writing cleaner and more modular code.

Key Points

  • Function expressions are functions stored in variables.
  • They can be anonymous (no name).
  • They are not hoisted, so you must define them before use.
  • Useful for callbacks and dynamic function creation.

Key Takeaways

Function expressions assign a function to a variable for flexible use.
They are not hoisted, so define them before calling.
Great for callbacks, event handlers, and modular code.
Can be anonymous, making code concise and clear.