Function Statements Vs Function Expression
Often JavaScript developers are found encountering the above question in their interviews. Both are ways to create functions and looks the same but there is a slight difference in them. Let's understand the difference and answer them appropriately to create a profound image before the interviewer.
Function Statement - When we declare a function with function keyword and a name with a body, it's called function statement.
Function Expression - When we assign a function to a variable, then it's called Function Expression. Below is an example to have a clear picture of them.
// Function Statement function a() { console.log("A Called"); }
a(); // Function Expression var b = function () { console.log("B Called"); } b(); Output - A Called B Called
Now what's the difference ? The answer lies in the concept of Hoisting. When we try to invoke the function before their declaration, Let's see how they behave :-
a(); b(); // Function Statement function a() { console.log("A Called"); } // Function Statement var b = function () { line 2 console.log("B Called"); } Output - A Called Uncaught TypeError : b is not a function // Error incase of invoking b()
When we try to invoke the function before they are declared, a() is works fine but b() throws an error. Reason - In case of Hoisting phase, a() is created a memory and assigned a memory. But b is treated like a variable it expects the function to be a value so it's assigned undefined initially and we can't call the function b() until the code hits the function declaration.
Hope, I am able to explain the difference. Please ignore the grammatical mistakes and try to grab the concepts. I will be trying my best to improve my writing skills.
Thanks for reading and "All the Best" for the future endeavours.