"Arguments over style are pointless. There should be a style guide, and you should follow it"
Variable is referenced to the Scope in which it is declared. If compiler is not able to find the reference to the variable in the scope it will go one step top and check if the reference is available and it do it until it reaches the global scope. This is called Nested Scopes which we will discuss later in this article. Now if you have the “Use Strict” than if the variable is not declared in Global Variable there will be error but if it is not set to use strict mode Global scope will declare that variable in his scope. If we have a variable declared without a var keyword in a function than it will be automatically declared in the global scope in non-strict mode but not in strict mode, but not in the case of functions if you make a call to a function which is not declared you will get a reference error.
With this one thing came to my mind about the difference between the function declaration and function expression. How can identify a function declaration and function expression? If function keyword is the first thing in the statement means it is function declaration. However, if it is not than it is an expression. Now function expression can be Anonymous function or name function. Anonymous function as the name suggest which does not have a name. So, a function expression without a name is called anonymous function expression and one with a name is called named function expression.
What is the difference between Anonymous and Named function expression?
- If it is named than you can refer to the function within the function scope. If you want to write a recursive function.
- It helps in the debugging, if there is no name to the function you will see anonymous function in the debug log. However,if you would have given the name than it would have been there in the Stack trace.
- Named function methods are self-documented. If we are using a name than we can understand that function would be doing but if it is anonymous than we need to check the function context to understand it.
Block Scope in ES6
In ES6 we have new keyword let keyword which make the variable scope implicit to the block in which is defined and not to the function scope. Block scope is pair of curly braces, and it is powerful enough and help us defined the least disclosure principle.
Let us look at the code examples
As you see you will get error if you refer j outside for loop, If you would have declared j using “var” if would be available outside for loop.
Note: to use let keyword you should defined the scope with ‘use strict’ mode. Otherwise it will give you an error.