Function vs Function Expression in JavaScript

You have learnt about both: Function declaration in JavaScript and Function Expression in JavaScript
We are going to learn it in detail.

When can be used?

I am not going to say that they have different syntax. We are better than that :D.

The main difference is when both are created and when it can be used?

The function expression is created when the execution reaches the very line where it is written in the script.
So you can not use the Function expression before it is created. Let us have a look at an example.


console.log(typeof(foo));
//output: "undefined"

foo();
//output: Uncaught ReferenceError: foo is not defined
//In production or while writing the code, please don't call foo before it is created 
//because it will stop the execution of the code and code below it won't be executed.
//we have added this code just for your understanding :)

let foo = function(){
    console.log("nice to meet you");
}

foo();
//output: nice to meet you
                    

As you can see, you can not call foo before it is created. It is undefined before it is created. After it is created, you can use it.
Now let us have a look at the function declaration.


console.log(typeof(foo));
//output: function

foo();
//output: nice to meet you

function foo(){
    console.log("nice to meet you");
}

foo();
//output: nice to meet you
                    

Did you see that? it is not magic. While using function declaration, you can use it anywhere in a block ( if a function is declared inside the block ) or in the whole script ( if a function is declared outside of block).

Recursive function

Most of the times, Recursive functions are created with function declaration.
If you want to use the recursive function with a function expression, then you should provide a name of the function. Because it will help you with execution stack while debugging.
Let us have a look at an example.


var factorial = function fac(n) { 
    return n < 2 ? 1 : n * factorial(n - 1);
};
console.log(6);
//output: 720
                    

Conclusion

In this section, you learned about the difference between function declaration and function expression. You should be knowing when to use function expression.
In next section, you will learn about the function scope in JavaScript.