Var, Let and Const — What's the difference?

Before ES6 (2015) there was one way to declare a variable. The keyword var.

var foo = 'baz';

The issue is that variables declared with var have a few problems.

Ambiguity

Using var means that you can declare a variable and mutate its contents. In honesty, we'll mostly declare a new variable in most instances and wait for a garbage collector to remove the old ones when finished being used. But, if there was an instance where the contents of that variable should not be changed, there was no way to stop another developer coming along and doing just that.

Foo, Foo, Foo

Peculiarly you can also redeclare the same variable again 😭 a recipe for disaster.

var foo = 'baz'; ✅ var foo = 'bar'; ✅

Scope

Var can have a global or function scope. What does this mean?

A variable that has a global scope, can be referenced anywhere in the program. Variables declared outside of functions using var will have a global scope.

A variable declared inside of a function will be scoped to that function. That means it cannot be referenced outside of it. So when the function finishes executing, that variable no longer exists. Pppft. Gone.

function foo() { let bar = 'baz'; console.log(bar); ✅ } console.log(bar); ❌

So what is the problem? Var doesn't have a block scope. What this means is that a variable declared inside of an code block (any code between two curly braces), will become a global variable and this is where the issue lies, because you now have the potentional of having conflicts between variables because you expected what you created inside code block to not be accessible outside.

With that knowledge, and the fact you can redeclare the same variable again......do you see the issues this can create?

var foo = 'bar'; if (cond) { var foo = 'baz'; } console.log(foo) // 'baz' 😭

RIP VAR

Enter let and const. These game changers cleaned that mess up.

No More Ambiguity

Declaring a variable with const tells JavaScript that this variable is a fixed value. Once you assign it a value, it will never change. Declaring a variable with Let will let JavaScript know that this can be changed later. It's as clear as that to JavaScript and other developers.

No Redecleration

When using let or const you cannot redeclare a variable. Once a binding name has been declared, you will get an error if you try to declare it again.

let foo = 'bar'; ✅ const foo = 'baz'; ❌

Block Scope for the win

No more global conflicts. Let and Const have global, function and block scope. This means you can create variables safely inside of your code blocks without fear that they will become global variables and introduce any bugs. Once the code block finishes executing, pfft, cloud of smoke, variables gone.

I hope that helps you understand var, let & const a little more. You may even be asked the difference in an interview one day, so it's useful to know. 😅

;