DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Difference Between var and let in Javascript

Before es6, we would only have 'var' to declare variables. But now we are given `var', 'let', and 'const', but we will only talk about differences between 'var' and 'let' in this.

There are issues with 'var' that may have led to the development of 'let'. They both are variable assignments but 'let' is more strict.

Using 'var' allows you to declare, redeclare, and update all within the same scope.

javascript
var num = 0
var num = 1
num = 2
console.log(num)
// prints out 2

'var' will not throw an error for reassignment. We may overwrite an important variable.
If we used 'let'

javascript
let num = 0
let num = 1

this will throw a redeclaration error. The case of updating using 'let' will not throw an error though.
javascript
let num = 0
num = 1

Another difference is how they work with scope.

javascript
var tool = "hammer"
var num = 0
if (tool == "hammer"){
var num = 3
}
console.log(num)
// num will output 3

In this example, the variable is reassigned and the output is taken from inside the function which may not be what we want.

In 'let' we will keep within our scope.

javascript
let tool = "hammer"
let num = 0
if (tool == "hammer"){
let num = 3
}
console.log(num)
// num will output 0

Top comments (0)