Two ways to create function
Let’s now jump into the concept of scope. Whenever we declare a variable by say var a = 10 , we are declaring it in global scope ie every part of our code can access it. We need them sometime but most time they create chaos.
So, we put the declaring in a scope and it’s only accessible within that scope. Treat scope as box and nothing can go outside it.
Consider the below figure.
Now the variable a is only accessible within it’s box. We can also have box within box. In the second example the inner scope/box have access to it’s variable b and also c. But the outer scope/box doesn’t have access to variable b.
In these language an if statement creates a scope and the below will give undefined when we try to access variable job.
if doesn’t creates scope
So, to create a scope in JS we put a variable inside a function.
JS scope by function
Now let’s see how to have a function not pollute the global namespace. Consider the below example.
Now, we created local variables a and b, but then created a global function myFunc. Sometime we don’t want this behaviour. So, in this case a IIFE (Immediately invoked Function expression) comes to the rescue. The above can be refactored as below.
In this we create an anonymous function and immediately invoked it.