The Difference Between Function Expression and Function Declaration in JavaScript

The Difference Between Function Expression and Function Declaration in JavaScript

Ferenc Almasi β€’ Last updated 2023 April 19 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Function expressions and declarations have two major differences. One is that for function expressions, you are assigning the function to a variable. In a function declaration, you don't:

Copied to clipboard! Playground
// Function expression
// Will throw a TypeError
console.log(func());
var func = function() { return 5; }

// Function declaration
// Will run without a problem, because it is hoisted
console.log(func());
function func() { return 5; }
functions.js

The biggest difference however is that expressions are not hoisted. If you call the function before it was initialized, you will get a type error:

Type error being thrown for function expression

Whichever you choose to use throughout your code, make sure you stay consistent to avoid unexpected behaviors.

Function expression vs declaration in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.