by Sai gowtham

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

In this tutorial, we are going to learn about what is difference between var functionName = function() {} and function functionName() {} in JavaScript

In JavaScript, we have two ways to declare a function.

First-way using function expression

We can declare a function in JavaScript by assigning a function to a variable which is called function expression.

// Uncaught TypeError: add is not a function
console.log(add(1,2));

var add = function(a,b){
    return a+b
}

Second-way using function declaration

// it works fine
console.log(add(1,2)); // 3

function add(a,b){
    return a+b;
}

Now let’s talk about the difference between the above two functions.

  • If a function is created by using the function expression that function is only available to use after the declaration.
  • If a function is created by using the function declaration that function is available anywhere in our script file.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course