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

David Y.

The Problem

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:

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.

Get Started With Sentry

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a JavaScript project and note your DSN

  3. Grab the Sentry JavaScript SDK

<script src="https://browser.sentry-cdn.com/7.104.0/bundle.min.js"></script>
  1. Configure your DSN
Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });

Check our documentation for the latest instructions.

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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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