Function statements vs Function expressions in JavaScript
When working with javascript, you must’ve come across this jargon and you might’ve wondered what these really mean. So let me try to simplify this for you.
Function statement(aka Function declaration) and function expression are the same thing except for a very tricky detail.
Let me elaborate with an example.
function statement()
{
console.log("This is a statement");
}
This is a function statement. This is basically how you define your functions in your code. Nothing new.
Now let’s do this a bit differently.
var expression = function()
{
console.log("This is an expression");
}
Now, this is a function expression. As you can see, the only difference here is that this function is created as an anonymous function and is assigned to a variable.
It doesn't necessarily have to be an anonymous function, but can be a named function as well.
var expression = function named()
{
console.log("This is an expression");
}
Now, let’s try to evaluate these two approaches to create a function.
function statement()
{
console.log("This is a statement");
}var expression = function()
{
console.log("This is an expression");
}statement();
expression();
Output:
This is a statement
This is an expression
Nothing surprising. Just as you expected. 😬
Now let’s try to invoke these functions before they are created. As you probably guessed, these functions should be hoisted during the memory creation and this should run smoothly, yes?
statement();
expression();function statement()
{
console.log("This is a statement");
}var expression = function()
{
console.log("This is an expression");
}
But, NO. 😑 Look at the output of this one.
This is a statement
Uncaught TypeError: expression is not a function
Strange right? 🤨 Not really.
During the hoisting, both of these functions get a memory allocated to them but only the function declared using function statements gets assigned to that memory. The function created using expressions behaves just like a normal variable. As you probably know, variables get assigned undefined as their initial value during hoisting and the real value is only assigned when the code is executed. Therefore if you try to invoke a function created using function expressions before it’s created, you will get an error.
So to summarize, the only difference between function statement and function expression is hoisting.
Thanks For Reading!