Isaac has a passion for coding, and has knowledge on web design, web development, and programming in general.
Variables declared both ways can store values, be it primitive values or objects, and may be initialized when created. They may also be null or undefined.
But now you want to know: what is the difference between var and let? The answer is scope.
In a second function called subtractTwo(), we expect to receive a number as a parameter, from which we intend to deduct 2 and return the result. But we are doing something wrong here. When deducting 2 from the parameter’s value, we use the numberTwo variable that we declared and initialized in our addTwo() function. By doing so, we are incorrectly assuming that the numberTwo variable is accessible outside its function, when in fact it is not.
Notice that this eventually causes our code to have an error. In Line 12, we pass in the value 10, which is stored in our global variable myNumber, to our addTwo() function. The output in the console is as expected, as we get the number 12.
The reason for this is clearly stated. The numberTwo variable that we are trying to access in Line 9 is inaccessible. It is thus not recognized, and because we have not declared any variable with the same name in our subtractTwo() function, there is no valid location in memory to reference, hence the error.
Understanding Scope Hierarchy
The latter is visible anywhere within the function. Finally, we have another function called childScope(), which has a local variable called accessHere. As you might have guessed by now, that variable can only be accessed in the function within which it is declared.
But our code generates an error, and that is because of a mistake in Line 13. On Line 16 when we call the parentScope() function, the console logging statements in both Line 11 and Line 13 get executed. Though the accessEverywhere variable gets logged without any issue, the execution of our code stops when we try to output the value of the accessHere variable in Line 13. The reason for that is that the variable in question was declared in the childScope() function and is therefore not visible to the parentScope() function.
Thankfully, there is an easy solution to that. We simply need to call the childScope() function without our parentScope() function definition.
You have seen examples of function-scoped variables above. Block scoped, nevertheless, means that the variable is only visible within the block of code within which it is declared. A block can be anything within curly brackets; take if/else statements and loops, for instance.
The piece of code above, with its comments, is self-explanatory. Let’s replicate it and make a couple of changes. In Line 3, we will use the let keyword, then try to access the hello variable in Line 4. You will see that our code will generate an error because of Line 6, as accessing a variable declared with let outside of its block scope is not allowed.
Should I use var or let?