Back to JavaScript
2025-12-085 min read

Function expressions (JavaScript)

Learn Function expressions (JavaScript) step by step with clear examples and exercises.

Why This Matters

Function expressions are an essential part of JavaScript's syntax, providing a powerful way to create reusable blocks of code and organize your scripts effectively. By mastering function expressions, you will be able to write more efficient, scalable, and maintainable code. In this lesson, we delve into the world of function expressions, offering practical examples, common mistakes, and answers to frequently asked questions.

Why This Matters

Function expressions are crucial for several reasons:

  1. Code reusability: By defining functions as expressions, you can create reusable code blocks that perform specific tasks or calculations.
  2. Organization: Function expressions help organize your code by breaking it down into smaller, manageable units. This makes it easier to maintain and understand the logic of complex scripts.
  3. Debugging: By isolating functionality within functions, you can more easily identify and fix issues when they arise.
  4. Preparation for job interviews: Many job interviews will require a solid understanding of function expressions as part of the JavaScript fundamentals.

Prerequisites

Before diving into function expressions, it's essential to have a strong foundation in the following concepts:

  1. JavaScript syntax and variables
  2. Basic data types (numbers, strings, booleans, null, undefined, and objects)
  3. Control structures (if-else statements, loops, and switch cases)
  4. Basic DOM manipulation (selecting elements and changing their properties)
  5. Understanding of JavaScript scoping rules
  6. Familiarity with arrow functions

Core Concept

Definition

Function expressions in JavaScript are blocks of code that define a function and can be assigned to a variable or passed as an argument to other functions. Function expressions are created using the function keyword followed by the function name, parameters (optional), and the code block enclosed in curly braces {}.

// Function expression example
let myFunction = function(param1, param2) {
// Function body
};

Function Hoisting

Unlike variable declarations, function declarations are hoisted to the top of their scope. However, function expressions are not hoisted and must be called after they have been defined.

// Function declaration example (hoisted)
function myFunctionDeclaration() {
// Function body
}
myFunctionDeclaration(); // This will work

// Function expression example
let myFunctionExpression = function myFunctionExpression() {
// Function body
};
myFunctionExpression(); // This will throw an error as the function has not been defined yet

Anonymous Functions

An anonymous function is a function expression that does not have a name. They are often used when a function is created and immediately called or passed as an argument to other functions.

// Anonymous function example
let result = (function(param1, param2) {
// Function body
return result;
})(value1, value2);

Worked Example

Let's create a simple function expression that calculates the product of two numbers and logs the result to the console.

let multiplyNumbers = function(num1, num2) {
let product = num1 * num2;
console.log(`The product is: ${product}`);
};

multiplyNumbers(5, 7); // Output: The product is: 35

Function Hoisting Example

Let's see how function hoisting affects function expressions and anonymous functions:

// Function expression example (not hoisted)
let myFunctionExpression = undefined;
console.log(myFunctionExpression()); // Outputs: TypeError: myFunctionExpression is not a function

let multiplyNumbers = undefined;
console.log(multiplyNumbers(5, 7)); // Outputs: undefined

// Assigning the function expression
myFunctionExpression = function() {
console.log('Hello, world!');
};

// Assigning the function expression to multiplyNumbers
multiplyNumbers = function(num1, num2) {
let product = num1 * num2;
console.log(`The product is: ${product}`);
};

myFunctionExpression(); // Outputs: Hello, world!
multiplyNumbers(5, 7); // Output: The product is: 35

Common Mistakes

  1. Forgetting to return a value: If your function expression doesn't explicitly return a value, it will implicitly return undefined.
let myFunction = function(param) {
// Do something
};
console.log(myFunction(5)); // Outputs: undefined
  1. Not understanding hoisting: Function declarations are hoisted to the top of their scope, but function expressions are not. This can lead to unexpected behavior if you're not careful.
  1. Not binding the correct this context: When using arrow functions, the this keyword behaves differently than in traditional function expressions. Ensure you understand how to bind the correct this context when necessary.

Arrow Function Mistakes

  1. Misunderstanding the this keyword: In arrow functions, the this keyword refers to the outer lexical scope. This can lead to unexpected behavior if not managed properly.
let user = {
name: 'John',
sayHello: function() {
console.log(`Hello, I am ${this.name}`);
}
};

let arrowFunction = () => {
console.log(`Hello, I am ${user.name}`); // Outputs: Hello, I am undefined
};

arrowFunction();
  1. Inability to use arguments: Arrow functions do not have access to the arguments object. Instead, you can use rest parameters or spread syntax to achieve similar functionality.

Practice Questions

  1. Write a function expression that takes three parameters and returns their sum.
let addNumbers = function(num1, num2, num3) {
return num1 + num2 + num3;
};
console.log(addNumbers(5, 7, 9)); // Output: 21
  1. Create an anonymous function that logs the current date and time.
let logCurrentTime = (() => {
let now = new Date();
console.log(`The current date and time is: ${now}`);
})();
  1. Given the following code, what will be logged to the console?
let myFunction = function() {
console.log(this);
};
myFunction.call({ name: 'Alice' });

FAQ

  1. What's the difference between a function declaration and a function expression?
  • A function declaration is defined using the function keyword followed by the function name, parameters (optional), and the code block enclosed in curly braces {}. Function declarations are hoisted to the top of their scope.
  • A function expression is created using the same syntax as a function declaration but is assigned to a variable or passed as an argument to other functions. Function expressions are not hoisted and must be called after they have been defined.
  1. What's an anonymous function?
  • An anonymous function is a function expression that does not have a name. They are often used when a function is created and immediately called or passed as an argument to other functions.
  1. Why can't I call a function expression before it has been defined?
  • Function expressions are not hoisted like function declarations, so they must be defined before they can be called. If you try to call a function expression before it has been defined, JavaScript will throw an error.
  1. Why does the this keyword behave differently in arrow functions compared to traditional function expressions?
  • In arrow functions, the this keyword refers to the outer lexical scope, while in traditional function expressions, the this keyword is determined by how the function was called. Understanding this difference can help you manage the this context when using arrow functions.
  1. How can I access the arguments passed to a function expression?
  • In traditional function expressions, you can use the arguments object to access the arguments passed to the function. However, in arrow functions, you should consider using rest parameters or spread syntax for similar functionality.
Function expressions (JavaScript) | JavaScript | XQA Learn