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

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay