The difference between: var functionName = function() {} and function functionName() {} in Javascript?
There are two ways of declaring functions in JS. Which are called function expression and a function declaration.
The first example is a function declaration:
function abc(){}
The second example is a function expression:
var abc = function() {};
Let’s see the difference between them:
function expression example code
The function expression is defined when that line is reached.
The function expression is often called an “anonymous function” because it does not have to have a name,
<!DOCTYPE html>
<html>
<body>
<script>
// TypeError: functionOne is not a function
functionOne();
var functionOne = function() {
console.log("Hello!");
};
</script>
</body>
</html>
function declaration example code
A function declaration is defined as soon as its surrounding function or script is executed (due to hoisting).
<!DOCTYPE html>
<html>
<body>
<script>
// Outputs: "Hello!"
functionTwo();
function functionTwo() {
console.log("Hello!");
}
</script>
</body>
</html>
Note: Hoisting is the JavaScript interpreter’s action of moving all variable and function declarations to the top of the current scope.
Performance test
Function declarations are faster (source: stackoverflow.com).
Do comment if you have any suggestions or questions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version