JavaScript Function Expressions

In JavaScript, a function expression involves creating a function and assigning it to a variable. This is different from a function declaration and is commonly used in modern JavaScript for more flexible and dynamic coding.



Basic Syntax

A function expression is a way to create a function and store it in a variable. This makes it easy to use the function later by calling the variable name.

Here's a simple example:

javascript
const greet = function() {
  console.log("Hello!");
};

greet();

Let’s break it down:

  • function() { ... } — This creates a function without a name. That’s why it’s called an anonymous function.
  • const greet = ... — The function is saved in a variable named greet. You can use this variable to run the function.
  • greet() — This calls the function and prints "Hello!" in the console.

Function expressions are useful when you want to:

  • Create a quick function and store it in a variable
  • Pass a function as an argument to another function
  • Use functions in places where you don’t need them globally

Function Expression vs Function Declaration

JavaScript allows you to define functions in two main ways:

  • Function Declaration – A traditional way to define a function using the function keyword.
  • Function Expression – A function assigned to a variable, often written without a name.

Let’s look at both with an example:

javascript
// Function Declaration
function greet() {
  console.log("Hello from declaration!");
}

// Function Expression
const sayHi = function() {
  console.log("Hello from expression!");
};

💡 Key Differences

  • Hoisting:
    Function declarations are hoisted — they can be called before they are defined in the code.
  • Function expressions are not hoisted — they must be defined first before you call them.

Here’s what that looks like in action:

javascript
greet(); // ✅ Works
function greet() {
  console.log("Hello!");
}

sayHi(); // ❌ Error: Cannot access 'sayHi' before initialization
const sayHi = function() {
  console.log("Hi!");
};

🧠 Summary

  • Use function declarations when you want your function available anywhere in the code.
  • Use function expressions when you want more control, such as assigning functions to variables or passing them as arguments.

Named vs Anonymous Function Expressions

In JavaScript, function expressions can be anonymous (no name) or named (have a name). Let’s see the difference.

🔹 Anonymous Function Expression

This type of function has no name. You usually assign it directly to a variable.

javascript
const sayHi = function() {
  console.log("Hi!");
};
  • function() — The function is created without a name (anonymous).
  • It’s stored in the sayHi variable.
  • You call it using sayHi().

🔹 Named Function Expression

A named function expression has a name. This name is only visible inside the function itself.

javascript
const sayHello = function sayHello() {
  console.log("Hello!");
};
  • function sayHello() — The function has a name.
  • It's still stored in a variable also called sayHello.
  • Named functions are helpful for debugging — their names appear in error messages and stack traces.

🧠 Tip: Even though you give the function a name, you still use the variable name to call it: sayHello().


Example 1: Basic Function Expression

Let’s create a simple function expression that adds two numbers together.

javascript
const add = function(x, y) {
  return x + y;
};

console.log(add(5, 3));

🧠 How It Works:

  • function(x, y): This creates an anonymous function that takes two parameters: x and y.
  • return x + y;: The function returns the result of adding x and y.
  • const add = ...: The function is stored in a variable named add.
  • add(5, 3): This calls the function with the values 5 and 3, and prints 8 to the console.

Output

8

Example 2: Function Expression Inside a Timer

Function expressions are often used when you want to run some code later — for example, with setTimeout. This lets you delay a function from running immediately.

javascript
setTimeout(function() {
  console.log("This message appears after 2 seconds.");
}, 2000);

🧠 How It Works:

  • setTimeout(...): This built-in function runs another function after a delay.
  • function() { ... }: This is an anonymous function expression — we don’t give it a name because it only needs to run once.
  • 2000: The delay is given in milliseconds. 2000 = 2 seconds.
  • After 2 seconds, the function runs and prints a message to the console.

Output (after 2 seconds)

This message appears after 2 seconds.

Example 3: Using a Function Expression with an Array

Function expressions are often used as callback functions — small functions that are passed into other functions to run later. A common example is using forEach to loop through an array.

javascript
const colors = ["red", "green", "blue"];

colors.forEach(function(color) {
  console.log("Color:", color);
});

🧠 How It Works:

  • colors.forEach(...): Loops through each item in the colors array.
  • function(color) { ... }: This is an anonymous function expression passed directly into forEach as a callback.
  • console.log("Color:", color): This line runs for each color in the array, printing its name.

Output

Color: red
Color: green
Color: blue

Exercises

1. Create a function expression that returns the square of a number.
javascript
const square = function(x) {
  return x * x;
};
console.log(square(4));

2. Write a named function expression and call it.
javascript
const logMessage = function logMessage() {
  console.log("This is a named function expression.");
};
logMessage();

3. Use a function expression inside a setTimeout.
javascript
setTimeout(function() {
  console.log("Executed after delay");
}, 2000);

Frequently Asked Questions

What is a function expression in JavaScript?

A function expression in JavaScript is a function that is defined within an expression, often assigned to a variable. It can be an anonymous function or a named function expression.


What is the difference between function declarations and function expressions?

Function declarations are hoisted, meaning they are available throughout the code, while function expressions are not hoisted and only available after their definition.


Can a function expression be anonymous?

Yes, a function expression can be anonymous, meaning it doesn't have a name. Anonymous functions are often used as arguments to other functions or immediately invoked.


What are the benefits of using function expressions?

Function expressions provide flexibility in JavaScript. They allow for defining functions on the fly and are useful for callback functions, event handling, and closures.


Can function expressions be used with 'new' keyword?

No, function expressions cannot be used with the 'new' keyword. Only function declarations can be used as constructors when using the 'new' keyword.



What's Next?

Next, you'll dive into Immediately Invoked Function Expressions (IIFE). You'll learn how to create self-executing functions that help in managing scope and preventing variable pollution in the global namespace.