There are different ways to define a function in javascript. I have seen these 2 ways to define and get confused with the differences then I googled and came across with some points which can help out to others to understand the difference between these.
Function Declaration vs Function Expression in JavaScript
The two ways are:
1 2 3 4 5 6 | var functionOne = function() { // Some code }; function functionTwo() { // Some code } |
The difference is that ‘functionOne‘ is defined at run-time, whereas functionTwo is defined at parse-time for a script block. For example:
1 2 3 4 5 6 | <script> functionOne(); var functionOne = function() { }; </script> |
It will show the error because functionOne is defined later than the calling.
1 2 3 4 5 6 7 | <script> // No error functionTwo(); function functionTwo() { } </script> |
In Strict mode, We can’t conditionally define functions using the second syntax:
1 2 3 4 5 6 7 | <script> "use strict"; if (conition) { // Error function functionOne() { doSomething(); } } </script> |
Without “use strict” this would not cause an error and functionOne will be defined irrespective of condition’s value.
If you want to alias functions on all browsers use this kind of declaration:
1 2 | function abc(){}; var xyz = abc; |
In this case both xyz and abc are aliases of the same object.
Basically when we define a function like this:
1 2 | function abc(){}; console.log(abc.name); // prints "abc" |
its name is automatically assigned. But when you define it like this:
1 2 | var abc = function(){}; console.log(abc.name); // prints "" |
its name is empty — we created an anonymous function and assigned it to some variable.
1 2 | var xyz = function abc(){}; console.log(xyz.name); // prints "abc" |
abc name is automatically assigned and assigned to a variable xyz like alias. so It prints “abc”.
So it is basically a difference between function declaration and function expression.