Video Lesson

Lesson Notes

Function Declarations vs Function Expressions in JavaScript

JavaScript offers two primary ways to define functions: function declarations and function expressions.


Function Declaration

1// Function declaration (hoisted) 2function add(numberOne, numberTwo) { 3 return numberOne + numberTwo; 4} 5 6// You can call it before its declaration due to hoisting: 7console.log(add(5, 5)); // 10
  • Always has a name (add in this case).
  • Hoisted: The entire function definition is moved to the top of its scope, so you can call it before it appears in the code.

Function Expression

1// Function expression (not hoisted) 2const add = function(numberOne, numberTwo) { 3 return numberOne + numberTwo; 4}; 5 6// Must be defined before use: 7console.log(add(1, 2)); // 3
  • Often anonymous (no name inside function).
  • Assigned to a variable (add).
  • Not hoisted: You cannot call it before the line where it’s defined, just like other variables.

Key Differences

  • Hoisting
    • Declarations are hoisted; expressions are not.
  • Definition Timing
    • Declarations are available throughout their scope immediately.
    • Expressions become available only after the assignment is executed.
  • Naming
    • Declarations always have a name.
    • Expressions can be anonymous or named, but exist only as the variable they’re assigned to.

When to Use Which

  • Function Declarations for core utilities you’ll call anywhere in the file.
  • Function Expressions when you want tighter control over when the function is available, or when passing functions as values (e.g., callbacks).

Choose the style that best fits your codebase and team conventions.

AI Assistant

Sign In Required

Sign in and subscribe to use the AI assistant for instant help with your lessons.

Sign In

Function Expressions

Learn the key differences between function declarations and function expressions. In this lesson, you'll learn how hoisting affects function usage, when to use each type for optimal code organization, and the nuances of naming, ensuring you write cleaner and more efficient JavaScript.

5m 22s

Course Content

0 of 32 lessons completed
6. Promises, Async and Await
0 of 0 completed
7. The DOM
0 of 0 completed