ES2015 (or ES6) introduced ii new ways to create variables, let and const. Merely before nosotros really dive into the differences between var, allow, and const, there are some prerequisites you need to know outset. They are variable declarations vs initialization, scope (specifically function telescopic), and hoisting.

Variable Declaration vs Initialization

A variable announcement introduces a new identifier.

Above we create a new identifier called declaration. In JavaScript, variables are initialized with the value of undefined when they are created. What that means is if we try to log the declaration variable, we'll get undefined.

            

var annunciation

panel . log ( declaration )

So if we log the declaration variable, we get undefined.

In contrast to variable declaration, variable initialization is when you first assign a value to a variable.

            

var declaration

console . log ( declaration )

annunciation = 'This is an initialization'

So here we're initializing the declaration variable by assigning it to a string.

This leads united states of america to our 2nd concept, Scope.

Scope

Telescopic defines where variables and functions are accessible inside of your program. In JavaScript, there are ii kinds of scope - global scope, and function scope. According to the official spec,

"If the variable argument occurs inside a FunctionDeclaration, the variables are defined with role-local telescopic in that function.".

What that means is if you create a variable with var, that variable is "scoped" to the function it was created in and is only accessible inside of that part or, whatever nested functions.

            

part getDate ( ) {

var date = new Engagement ( )

return appointment

}

getDate ( )

console . log ( engagement )

Above we try to access a variable outside of the function it was declared. Considering date is "scoped" to the getData function, information technology'south simply accessible inside of getDate itself or any nested functions inside of getDate (every bit seen below).

            

role getDate ( ) {

var date = new Date ( )

function formatDate ( ) {

return date . toDateString ( ) . slice ( iv )

}

return formatDate ( )

}

getDate ( )

console . log ( date )

Now let's look at a more than advanced instance. Say we had an array of prices and we needed a function that took in that array as well as a disbelieve and returned united states of america a new assortment of discounted prices. The stop goal might look something like this.

            

discountPrices ( [ 100 , 200 , 300 ] , .5 )

And the implementation might look something like this

            

part discountPrices ( prices , discount ) {

var discounted = [ ]

for ( var i = 0 ; i < prices . length ; i ++ ) {

var discountedPrice = prices [ i ] * ( ane - discount )

var finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

return discounted

}

Seems unproblematic enough but what does this have to do with cake scope? Take a expect at that for loop. Are the variables declared inside of it accessible exterior of it? Turns out, they are.

            

function discountPrices ( prices , discount ) {

var discounted = [ ]

for ( var i = 0 ; i < prices . length ; i ++ ) {

var discountedPrice = prices [ i ] * ( 1 - discount )

var finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

console . log ( i )

panel . log ( discountedPrice )

console . log ( finalPrice )

return discounted

}

If JavaScript is the simply programming language yous know, you may non think anything of this. All the same, if yous're coming to JavaScript from some other programming language, specifically a programming language that is blocked scope, you lot're probably a footling fleck concerned almost what's going on here. It's not really cleaved, it's only kind of weird. At that place'due south non really a reason to still have access to i, discountedPrice, and finalPrice outside of the for loop. It doesn't really do us any proficient and it may even cause us damage in some cases. All the same, since variables declared with var are part scoped, you do.

Now that nosotros've discussed variable declarations, initializations, and scope, the last thing nosotros demand to affluent out before we dive into let and const is hoisting.

Hoisting

Remember earlier we said that "In JavaScript, variables are initialized with the value of undefined when they are created.". Turns out, that's all that "Hoisting" is. The JavaScript interpreter will assign variable declarations a default value of undefined during what's chosen the "Creation" phase.

For a much more than in depth guide on the Cosmos Phase, Hoisting, and Scopes see "The Ultimate Guide to Hoisting, Scopes, and Closures in JavaScript"

Let's take a look at the previous example and come across how hoisting affects it.

            

function discountPrices ( prices , disbelieve ) {

var discounted = undefined

var i = undefined

var discountedPrice = undefined

var finalPrice = undefined

discounted = [ ]

for ( i = 0 ; i < prices . length ; i ++ ) {

discountedPrice = prices [ i ] * ( 1 - disbelieve )

finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

console . log ( i )

console . log ( discountedPrice )

console . log ( finalPrice )

return discounted

}

Notice all the variable declarations were assigned a default value of undefined. That'south why if you effort access one of those variables before it was actually declared, you'll just become undefined.

            

function discountPrices ( prices , discount ) {

panel . log ( discounted )

var discounted = [ ]

for ( var i = 0 ; i < prices . length ; i ++ ) {

var discountedPrice = prices [ i ] * ( 1 - discount )

var finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

console . log ( i )

console . log ( discountedPrice )

panel . log ( finalPrice )

render discounted

}

Now that yous know everything in that location is to know nearly var, let'due south finally talk virtually the whole point of why yous're hither, what's the departure between var, allow, and const?

var VS allow VS const

Showtime, permit's compare var and let. The main divergence betwixt var and let is that instead of being function scoped, allow is block scoped. What that ways is that a variable created with the let keyword is available inside the "block" that information technology was created in as well as whatever nested blocks. When I say "block", I mean annihilation surrounded by a curly brace {} like in a for loop or an if argument.

And so allow's look back to our discountPrices function one terminal time.

            

function discountPrices ( prices , discount ) {

var discounted = [ ]

for ( var i = 0 ; i < prices . length ; i ++ ) {

var discountedPrice = prices [ i ] * ( ane - discount )

var finalPrice = Math . circular ( discountedPrice * 100 ) / 100

discounted . button ( finalPrice )

}

console . log ( i )

console . log ( discountedPrice )

panel . log ( finalPrice )

return discounted

}

Remember that we were able to log i, discountedPrice, and finalPrice outside of the for loop since they were declared with var and var is part scoped. But now, what happens if we alter those var declarations to employ let and endeavor to run it?

            

function discountPrices ( prices , discount ) {

let discounted = [ ]

for ( let i = 0 ; i < prices . length ; i ++ ) {

let discountedPrice = prices [ i ] * ( 1 - discount )

let finalPrice = Math . circular ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

panel . log ( i )

console . log ( discountedPrice )

console . log ( finalPrice )

render discounted

}

discountPrices ( [ 100 , 200 , 300 ] , .five )

🙅‍♀️ We get ReferenceError: i is not defined. What this tells u.s. is that variables declared with let are block scoped, not office scoped. And so trying to access i (or discountedPrice or finalPrice) outside of the "block" they were alleged in is going to give united states a reference error every bit nosotros just barely saw.

            

var VS let

var: part scoped

allow: block scoped

The adjacent difference has to do with Hoisting. Earlier we said that the definition of hoisting was "The JavaScript interpreter will assign variable declarations a default value of undefined during what'due south called the 'Creation' phase." We even saw this in action by logging a variable before information technology was declared (you become undefined)

            

part discountPrices ( prices , disbelieve ) {

console . log ( discounted )

var discounted = [ ]

for ( var i = 0 ; i < prices . length ; i ++ ) {

var discountedPrice = prices [ i ] * ( ane - discount )

var finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

console . log ( i )

panel . log ( discountedPrice )

console . log ( finalPrice )

return discounted

}

I can't think of any use case where yous'd actually desire to admission a variable earlier information technology was declared. It seems like throwing a ReferenceError would be a better default than returning undefined. In fact, this is exactly what let does. If yous try to access a variable declared with let earlier it's declared, instead of getting undefined (similar with those variables declared with var), you'll get a ReferenceError.

            

function discountPrices ( prices , disbelieve ) {

console . log ( discounted )

permit discounted = [ ]

for ( let i = 0 ; i < prices . length ; i ++ ) {

let discountedPrice = prices [ i ] * ( 1 - disbelieve )

let finalPrice = Math . round ( discountedPrice * 100 ) / 100

discounted . push ( finalPrice )

}

console . log ( i )

console . log ( discountedPrice )

console . log ( finalPrice )

return discounted

}

            

var VS allow

var:

function scoped

undefined when accessing a variable before it'southward declared

permit:

cake scoped

ReferenceError when accessing a variable before information technology'south declared

let VS const

Now that you understand the difference betwixt var and let, what about const? Turns out, const is almost exactly the same every bit permit. Withal, the only difference is that in one case you've assigned a value to a variable using const, y'all tin't reassign it to a new value.

            

let name = 'Tyler'

const handle = 'tylermcginnis'

proper noun = 'Tyler McGinnis'

handle = '@tylermcginnis'

The take away to a higher place is that variables declared with allow tin can be re-assigned, merely variables declared with const can't be.

Cool, then anytime you want a variable to exist immutable, y'all tin can declare it with const. Well, not quite. Only because a variable is alleged with const doesn't hateful information technology'due south immutable, all information technology means is the value tin can't be re-assigned. Here's a adept example.

            

const person = {

proper noun : 'Kim Kardashian'

}

person . name = 'Kim Kardashian Due west'

person = { }

Notice that changing a property on an object isn't reassigning it, then even though an object is declared with const, that doesn't mean yous can't mutate whatsoever of its properties. It simply means you can't reassign it to a new value.


At present the near important question we haven't answered yet, should y'all utilise var, let, or const? The well-nigh popular stance, and the opinion that I subscribe to, is that you should always employ const unless you know the variable is going to change. The reason for this is past using const, you lot're signalling to your future self likewise as whatsoever other future developers that have to read your code that this variable shouldn't change. If it volition need to change (like in a for loop), y'all should use allow.

So between variables that change and variables that don't change, at that place's not much left. That means yous shouldn't ever have to use var once again.

Now the unpopular stance, though information technology still has some validity to information technology, is that you lot should never use const because fifty-fifty though you lot're trying to signal that the variable is immutable, every bit we saw above, that's not entirely the case. Developers who subscribe to this opinion ever use let unless they have variables that are actually constants similar _LOCATION_ = ....

So to epitomize, var is part scoped and if you lot endeavor to use a variable declared with var earlier the actual proclamation, yous'll just go undefined. const and let are blocked scoped and if yous try to use variable declared with let or const earlier the declaration you'll get a ReferenceError. Finally the difference betwixt let and const is that once you've assigned a value to const, you lot can't reassign it, but with permit, you can.

            

var VS let VS const

var:

function scoped

undefined when accessing a variable before it'southward declared

allow:

block scoped

ReferenceError when accessing a variable before information technology's declared

const:

block scoped

ReferenceError when accessing a variable earlier information technology'due south alleged

tin't exist reassigned


Earlier you lot leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the final fourth dimension yous actually looked forward to getting one? Fifty-fifty worse, when's the last fourth dimension you actually read one rather than just skim it?

We wanted to change that, which is why nosotros created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 72,351 subscribers and an almost fifty% weekly open charge per unit afterward, it looks similar nosotros did it.

Delivered to 72,351 developers every Monday

    Avatar for @sduduzo_g

    This is the kickoff ever newsletter that I open up a music playlist for and maximize my browser window just to read it in peace. Kudos to @uidotdev for peachy weekly content.

    Avatar for @flybayer

    The Bytes newsletter is a work of art! It'southward the only dev newsletter I'chiliad subscribed too. They somehow take semi ho-hum stuff and infuse information technology with only the right amount of comedy to make you chuckle.

    Avatar for @johnhawly

    Bytes has been my favorite newsletter since its inception. It's my favorite thing I wait forward to on Mondays. Goes not bad with a hot cup of java!

    Avatar for @garrettgreen

    Garrett Dark-green

    @ garrettgreen

    I subscribe to A LOT of dev (especially JS/TS/Node) newsletters and Bytes by @uidotdev is ever such a welcomed, enjoyable alter of pace to most (funny, lighthearted, etc) just notwithstanding comprehensive/useful.

    Avatar for @mhashim6_

    Literally the but newsletter I'thou waiting for every week.

    Avatar for @graysonhicks

    Grayson Hicks

    @ graysonhicks

    Bytes is the developer newsletter I most wait forward to each week. Great residue of content and context! Thanks @uidotdev.

    Avatar for @mitchellbwright

    Mitchell Wright

    @ mitchellbwright

    I know I've said information technology before, but @tylermcginnis doesn't miss with the Bytes email. If you're a developer, yous really demand to subscribe

    Avatar for @aspittel

    Can I only say that I giggle every time I get the @uidotdev electronic mail each week? You should definitely subscribe.

    Avatar for @thefinnomenon

    Every JavaScript programmer should be subscribed to the newsletter from @uidotdev. Not but practice they manage to succinctly cover the hot news in the JavaScript world for the week just information technology they manage to add a refreshing humour to it all.