Function Declaration vs Function Expression: What’s the Difference?

We would have studied in maths that a function is something where it takes some gebrish and return some other gebrish.
Okay!! Let's Start from Beginning.
When we write a programs, we often repeat the same logic many times for example i want to add two number how would a noob will do the same thing?
console.log(5 + 3) Output ->8
console.log(10 + 2) Output ->12
console.log(7 + 6) Output -> 13
Here we are doing addition again and again. what if i write something and i give it my two number and by doing some magic it returns me the ans without of me adding + + + again and again for all operation. That magic is called function
A function is a reusable block of code that performs a task.
Write it once and use it many times.
function add(a, b){
return a + b;
}
// This is the one time we need to define the function
// Basically making a function
But wait how to use it?
console.log(add(2,3)) // calling the function and printing it
so using of a function is calling calling of function and making of function is called declaration.
Now i can re use it again and again, let's see the whole code and dry run!
function add(a,b){
console.log(a+b);
}
add(2,3);
add(2,5);
Output
5
7
Now we know some sort of function!
Function Expression
A function can also be stored inside a variable.
Example:
let add = function(a, b){
return a + b;
}
console.log(add(5,3))
Output
8
Here the function does not have its own name.
It is stored inside the variable add.
Declaration vs Expression
Side by side comparison.
Function Declaration
function greet(){
console.log("Hello")
}
Function Expression
let greet = function(){
console.log("Hello")
}
Both create functions, but the way they behave in memory is slightly different.
Basic Idea of Hoisting
JavaScript moves some declarations to the top of the scope during execution.
This behavior is called hoisting.
Function Declaration Hoisting
This works:
greet()
function greet(){
console.log("Hello")
}
Output:
Hello
Even though we called the function before defining it, it still works.
Because function declarations are hoisted.
Function Expression Hoisting
This does not work:
greet()
let greet = function(){
console.log("Hello")
}
Error occurs because the variable greet is not ready yet.
Function expressions behave like normal variables, so they are not available before assignment.


