Explain the differences on the usage of foo between function foo() {} and var foo = function() {} in JavaScript
By FrontendPro Editorial Team Updated 8/8/2026
Answer
function foo() {} is a function declaration while var foo = function() {} is a function expression. The key difference is that function declarations have their bodies hoisted but the bodies of function expressions are not (they have the same hoisting behavior as var-declared variables).
If you try to invoke a function expression before it is declared, you will get an Uncaught TypeError: XXX is not a function error.
Function declarations can be called in the enclosing scope even before they are declared.
foo(); // 'FOOOOO'
function foo() {
console.log("FOOOOO");
}
Function expressions if called before they are declared will result in an error.
foo(); // Uncaught TypeError: foo is not a function
var foo = function () {
console.log("FOOOOO");
};
Another key difference is in the scope of the function name. Function expressions can be named by defining a name after the function keyword and before the parentheses. However, when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or undefined.
const myFunc = function namedFunc() {
console.log(namedFunc); // Works
};
myFunc(); // Runs the function and logs the function reference
console.log(namedFunc); // ReferenceError: namedFunc is not defined
Note: The examples use var due to legacy reasons. Function expressions can be defined using let and const, and the key difference is in the hoisting behavior of those keywords.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
