What I learned is there are three ways function can be defined : a) Function Declaration b) Function Expression c) Arrow Function
Function Expression and arrow function can be simply defined and assigned to a variable but we cant do this for Function Declaration.. Am i right?
but I tried a code as follow:
const square_a_num = function square_the_num(num){
return num**2
}
const square_45 = square_a_num(45)
console.log(square_45);
I think the way I defined the function above is Function declaration but still I was able to assign it to a variable., and it is still working.
I hoped if I declared it like a function expression like below then only I can assign it to a variable :
const square_a_num = function(num){
return num**2
}
const square_45 = square_a_num(45)
console.log(square_45);
Where I am making mistake?
Thanks
I thought it should have given me an error message but rather it gave me the output as 2025 .
2
Answers
This will give error when function is defined as expression i.e. assigned to a variable then original name of function is not the actual function rather the variable name becomes the funciton name
Doubt : how the above code worked , if it was defined like function declaration , how could we assign it to a variable
Answer : function expression means when we declare a function and assign it to a variable, in such case the name of function is irrelevant because the variable name (square_a_num) now becomes the function name and function can now be called only with this variable name and not with the function name (square_the_num)that we gave , so its better not to give name.
This is still interpreted as a function expression, except that it has a name.
This allows function expressions to be recursive.
Read more here
If you try to execute
square_the_num()
outside of it’s own scope, you will get:ReferenceError: square_the_num is not defined