- You don’t need to declare a variable before using it, unlike other programming languages that provide better compile time support and syntactic sugar. Variables that are not declared are hoisted to global scope.
- You can declare global functions as well using var keyword by defining them outside a method.
- Since var creates a function scoped variable it can cause unexpected results with loops.
Let’s try to understand various problems occurring because of this and why its concept wise different from a developer coming from C# or Java background.
Scenario 1: Accidentally global variables
Consider below code which accidentally declares a global variable by not using var keyword
Off-Course you can work-around by running scripts in strict mode using below code to get error instead of accidentally promoting variables to global store if variables are not defined and meant to be local only.
Scenario 2: Hoisting
Output Comes as
Here is modified version from the eyes of compiler
Scenario 3: var as global variable
Consider below code where we have declared variable a outside a method. Once declared it comes in global scope and will be accessible in other script blocks as well.
ES-6 has introduced let keyword which helps in defining scopes in a better way.
Let keyword is block-scoped unlike var keyword which is function scoped
Let’s rewrite code in scenario 2 using let keyword
SCRIPT5009: ‘a’ is undefined
Scenario 4: var inside loop statements
In below code, we are pushing a function inside a function array. As per logic, the function will log the captured value of index once invoked and expected out is numbers from 0 to 4. Let’s check
So, the output is not what we expected. Since variable index goes into function scope and when we actually invoke functions, they used the current value of index i.e. 5. While creating functions that do not return immediately (like in our example) this is a real cause of concern and we can work-around by create IIFE (Immediately Invoked function expressions) which actually capture the value of variables rather than delaying it till actual usage. Here is an IIFE version above code
Above code works as expected and prints value 0-4. This is because the current value of variable at the time of loop execution was captured inside the arrays. But as you can see we need to work around something which is available by default in other programming language. And again let keyword comes to rescue.
Below is a refactored version using let keyword which works as expected without workaround