Scope and behavior of var, let, and const for beginners

let’s start with the var variable declaration as you probably learning with let and const. Var was used in JavaScript prior to ES6 to declare and assign variables. Var is loose in it’s behavior; it can be reassigned and it’s scope depends on how/when it is declared or it’s lexical environment.

Test this out: in your console. Hit F12 key(on windows) and then declare a variable with var. then reassign it the next line down. What happened? No errors, no complaints, everything was just alright alright alright.

This is the reason var was discontinued and replaced with let and var. Perhaps you don’t want your variables reassigned. The people who decide what JavaScript is wanted to give you a way to declare variables that don’t change.

The scope for var is global if it is outside of a function. That does not mean that you will have access to it though. You cannot use the var variable before you declare and assign it. It is not hoisted meaning the JavaScript parser reads your file then executes it. If it encounters a function it will hoist it. This means that it will know the function exists and not create errors. Once declared var is now part of the lexical environment meaning the code around it. However if you declare a var variable in a function it will be private to that function.

You can see when you ask JavaScript what x is it tells you what you assigned it to above. The variable declared and assigned in the function is now private. When you call global it tells you 100 which is the value you set x to within the function.

This demonstrates that var can be reassigned and that it’s scope is different depending on the lexical environment; in a function it is private to that function. Otherwise it is a global scope.

The example above is exactly why const and let were created in ES6.

These are both like var but not like var. Let’s start with Const.

Const let’s you declare and assign a variable. However if the example above we used const instead of var the code would break. Const does not let you reassign variables. If you know something is not going to change in your code use const. The standard is to always use const unless you know you need to change something. As soon as you assign a variable it becomes immutable. This is for primitive datatypes. Objects and functions can be altered in that their variables within them can be altered but you cannot reassign a const Object to be a different Object.

Let is more forgiving. This is vary much like var except it is bock scoped. In fat the only difference is that var let have different scopes and let is more strict. Let and Const is block scoped. A block is essentially anything within “{“ and “}”. It can also be a function, if, switch, and for. All of these are also blocks.