Variables

Variables are an important part of programming. They let as give a name to values, which makes code easier to understand, easier to write, and easier to reuse.

There are a few different types of variables which we can create and they are all similar, but have some distinct differences.

Var

The first (and oldest) type of variable we can make are those defined with the var keyword. These variables get hoisted. Hoisting is JavaScript's default behaviour of moving all declarations to the top of the current scope (to the top of the current script or the current function). This means that the following code will work

x = 5; // Assign 5 to x

console.log(x) // use the value inside x

var x; // Declare x

Let

Variables defined with the let keyword will work almost the same as var but they will not be hoisted, so the following will NOT work.

y = 5; // Assign 5

console.log(y) // use the value inside

let y; // Declare

This will throw an error like Uncaught ReferenceError: Cannot access 'y' before initialization

Even though it may seem odd, this is generally preferred behaviour, because it forces the dev to write more deliberate, thoughtful code. Being able to use variables before you declare them can make things confusing and hard to debug.

Const

Variables defined with const are called "constants" and just like those declared with let , they are NOT hoisted. They also have another behaviour, which is that they cannot be reassigned. Once the variable has been declared, the value stored inside it cannot be replaced. Again, this might seem like odd restrictive behaviour, but it is also often desired - more often than not.

Having a built in guarantee that your values aren't going to get replaced somewhere in the code is sort of like a comforting safety net, and removes something which you might otherwise have to worry about when working with less strict variables. You can always declare more variables if you need to, there is rarely a need to reassign an existing one, but when there is, we can always use let.

Last updated