Sentry Answers>JavaScript>

Difference between `var functionName = function() {}` and `functionName() {}` in JavaScript

Difference between `var functionName = function() {}` and `functionName() {}` in JavaScript

David Y.

The ProblemJump To Solution

What is the difference between var functionName = function() {} and functionName() {} in JavaScript?

The Solution

We call var functionName = function() {} a function expression and functionName() {} a function declaration.

  • We use a function expression to assign a function as the value of a variable.
  • We use a function declaration to declare a function to be used anywhere in our scope.

Function expressions are only evaluated when the JavaScript interpreter reaches their line of code, whereas function declarations are evaluated at the start of execution. We can see the difference in this code snippet:

Click to Copy
functionExpressed(); // will throw a TypeError, as functionExpressed is not yet defined var functionExpressed = function() { console.log('Executing functionExpressed...'); }; functionExpressed(); // will print "Executing functionExpressed..." as it is now defined functionDeclared(); // will print "Executing functionDeclared..." even though we only define the function below this call function functionDeclared() { console.log('Executing functionDeclared...'); }

In most simple cases, we will want to use function declarations, but it can sometimes be useful to have a function that is only defined after other code has run. Function expressions give us more control over the code flow at the expense of having to be more careful about where we place individual statements.

  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.