DEV Community

Var, let and const- what's the difference?

Sarah Chima on October 25, 2017

A lot of shiny new features came with ES2015 (ES6) and since it's 2017, it's assumed that a lot of JavaScript developers have become familiar with ...
Collapse
 
abhijeetckar92 profile image
abhijeetckar92 • Edited

this is a good article..however you should update your last example
const flow = {
message : "say Hi",
times : 4
}

to

const greeting = {
message : "say Hi",
times : 4
}

don't know how anybody who's reading this article missed that!

Collapse
 
abdushaker profile image
Abdu Shaker

I noticed something did not add up but I didn't pay attention to the details since I got what I was looking for. Good catch, tho.

Collapse
 
bkmillanzi profile image
Bkmillanzi

left me in blanks... I am glad you had pointed it out! Thanks'
and btw, the article is indeed one of the best!

Collapse
 
sarah_chima profile image
Sarah Chima

thank you

Collapse
 
curiousconfuseddev profile image
Ansh

It's updated now. Thanks for notifying

Collapse
 
ramachowdary profile image
rama-chowdary

Yeah

Collapse
 
domin profile image
Dominic Sears

For a noob like me, this explained "let" declarations for me.

Collapse
 
sarah_chima profile image
Sarah Chima

I'm glad it did.

Collapse
 
jeansberg profile image
Jens Genberg

Good post. I wasn't sure about these. Just knew that 'var' should be avoided.

I think you have typo here. Remove the second 'let' from the first code block. :)
So while this will work,
let greeting = "say Hi";
let greeting = "say Hello instead";
this will return an error.
let greeting = "say Hi";
let greeting = "say Hello instead";//error: Identifier 'greeting' has already been declared

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks a lot for pointing that out. I'll correct it right away.

Collapse
 
itayko profile image
itayko

Thank for a great article

Error still exists in the article..

Collapse
 
ashbrandn profile image
Ashley Brandon

Why should var be avoided?

Collapse
 
sgmallon profile image
Scott Mallon • Edited

'Var' allows for re-declarations in code which does not throw errors and can create unintended side-effects in your code.

'Let' allows for variable reassignment but not for duplicate declarations (block-scoped), much like strongly typed languages like C# and Java.

'Const' allows for declaration once and for assignment once, and can never be re-declared or reassigned (block-scoped). For instance, I use 'const' for inline function declarations, so that I don't accidentally redefine this function's behavior at some later point in time by mistake. Even though I am unlikely to do so, it is just safer for myself and others to work on.

To paraphrase Sarah more generically:

"While it is not a problem if you knowingly want a var to be a certain value at a certain point in code, it becomes a problem when you do not realize that this same var has already been declared/defined before or, even worse, has had other functions operate on this var without your knowledge."

So, in other words, it's a much better idea to use 'let' and 'const' in order have safer control over your variables and constants.

Thread Thread
 
oizabaiye profile image
Oiza

This was incredibly helpful, and a great TLDR!

Collapse
 
mushin108 profile image
Mushin108

"Variable shadowing"

Collapse
 
olawanle_joel profile image
Joel Olawanle • Edited

const alone does not guarantee protection for your data or let me say it does not protect your data from mutation,

Example:

const GREETING = {
    name : "Joel",
    info : "Goodday!"
 }
Enter fullscreen mode Exit fullscreen mode

Though the above code makes use of const i can still update the values via the code below

GREETING.name = "Elijah";
Enter fullscreen mode Exit fullscreen mode

But this could easily be avoided by making use of Object.freeze() to freeze our const variables.
Just add this line of code and you will discover that the values cannot be updated.

Object.freeze(GREETING); 

GREETING.name = "Elijah"; // This will now be ignored due to mutation
Enter fullscreen mode Exit fullscreen mode

For more clarification check: freecodecamp.org/learn/javascript-...

Collapse
 
avrani profile image
Ariel

Hi, great article but I think you have a mistake about the hoisting,you wrote:
"They are all hoisted to the top of their scope but while var varvariables are initialized with undefined, let and const variables are not initialized."
If you will look at the JavaScript Hoisting section in w3schools.com website,
you will notice that:"Variables and constants declared with let or const are not hoisted!"
Please check in:
w3schools.com/js/js_hoisting.asp

Collapse
 
mohammedyehia profile image
Mohammed

According to MDN and ECMA 2015 her words are right
check this developer.mozilla.org/en-US/docs/W...

Collapse
 
sobhardwaj profile image
Siddharath shankar bhardwaj

That's exactly I m thinking the new let and const in javascript are not hoisted..she wrote wrong things..u should correct this article..do not mislead people with this ??

Collapse
 
kramffud profile image
Mark Duff

Years later, this is still the most concise explanation and welcomed even by those of us who are not lightweights - but don't stray into the JS badlands much. You have great teacher chromosomes, Sarah. Ignore the nit-pickers - this is still the best explanation primarily because of its brevity.

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks for the kind words, I really appreciate it.

Collapse
 
wolf00bomber profile image
Wolf00Bomber

The article is well written, but the problem is with the visualization of the concepts, if only these were depicted in pictorial or tabular format, can have immense effect on readers. Thanks for the article thought.

Collapse
 
full_stackgeek profile image
Full Stack Geek

That's a great article. Inspired me to write:

Var is function-scoped and not block-scoped which means that constructs like if statements, while loops etc do not create new scopes while using var. It also means that, as var is function-scoped, if we do not create a function, we do not create new scope while using var.

Read More here:

Var vs Let in JavaScript

Collapse
 
gamebecks profile image
gamebecks

Hi, you have said that variable declared as var will have global scope if declared outside a function. But the same can even be said for variables declared as let and const. They indeed are locally scoped but when done outside a function, they will have global scope like var.
Please correct me if am wrong?

Collapse
 
nicksu86 profile image
NickSu86

Thank you for your post, I am a newbie to Nodejs and quite confusing on when to use let, const or var. As I saw some require a module with var while some with const, could you advise which is better when requiring a module? After reading your post, I think const is better to require another module because it will never change.
One more question could you please do me a favor to explain the memory usage between these three, is there any different other than scope, thank you

Collapse
 
vnsc16 profile image
Victor Sanchez

I've finally understood.
(Again) 'Cause I had forgotten hehe 😹😹
Thanks ♥

Collapse
 
hexiaosheng profile image
hexiaosheng

very helpfully, many thanks

Collapse
 
elecrei profile image
Ryan

Thanks for the explanations on the differences between var, let and const. When I first heard of let and const I was so confused. I wanted to know though is var still good to use and how should it be used when compared with let and const?

Collapse
 
erkanokman profile image
Erkan Okman

var erkan = 3;
if (erkan == 3) {
var erkan = 2;
console.log(erkan); //2
}
console.log(erkan); //2

//////////////

let erkan = 3;
if (erkan == 3) {
let erkan = 2;
console.log(erkan); //2
}
console.log(erkan); //3

//////////////

const erkan = 3;
if (erkan == 3) {
const erkan = 2;
console.log(erkan); //2
}
console.log(erkan); //3

Collapse
 
saradasutar profile image
Sarada Sutar

Thanks, Good article on concept of using var, let and const.

Collapse
 
niksolaz profile image
Nicola Solazzo

Good article, if you are interested you could read my article on the same topic. Maybe an exchange of ideas :)
medium.com/notonlycss/difference-b...

Collapse
 
mahesh__nandam profile image
Mahesh Nandam • Edited

Demystified the topic with your narration, Thank you.

Collapse
 
shareazc profile image
Shareni Azcárraga

Thank you so much, really cleared things up for me!

Collapse
 
pablofr10 profile image
Pablo Martinez

The best explanation that I see on Internet. Thanks!

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you for your kind words.

Collapse
 
lancejohnson profile image
Lance Johnson

Thanks Sarah! Great, simple explanation.

Collapse
 
chetanupreti profile image
chetanupreti

let me clear about const.

const used when we don't want to reinitialize the variable values.

like

const a=[2,3,4];

a[1]++; //doesn't give error;

a=[3,4]; //give error;

that's about const.

Collapse
 
sgmallon profile image
Scott Mallon

The cleanest explanation I've seen so far of let vs. const vs. var.

Collapse
 
mrichardstweets profile image
Megan Richards

Great article! Super thorough, but clear enough for a beginner like me to understand. Thank you!

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks Megan, I'm glad you like it.

Collapse
 
abdushaker profile image
Abdu Shaker

I love the simplicity and consistency of the examples. They made the difference very clear. Thanks a lot.

Collapse
 
arung86 profile image
Arun Kumar G

In a global scope var will be associated with global object
where as let and const are not
ex: window.var_variable
not supported by let and const

Collapse
 
nikhilchugh161 profile image
Nikhil Chugh

Thanks for this article, it really helps me understand these basic concepts well.
Thanks a lot!

Collapse
 
mang0g0rilla profile image
mang0g0rilla

Excelent article, thank yoU!

Collapse
 
msahith profile image
Msahith

absolutely nice article ,thumbs up

Collapse
 
kgcodes profile image
Kelvin Graddick

This was great; I learn a lot and tightened up my knowledge in 5 minutes 🙌🏾

Collapse
 
nagendra226 profile image
Nagendra

Thank you so much. It was very easy to understand.

Collapse
 
dasp817 profile image
Dastin Prater

Awesome article. Very well structured and easy to understand.

Collapse
 
rainyman2012 profile image
Ehsan

Thank you.

Collapse
 
abrahamghaemi profile image
Abraham ghaemi

nice :)

Collapse
 
npandey25 profile image
nitish pandey

Some typos in there though. You have used an object flow accidentally. Two varying illegal examples of const look identical to me. Do check. Or did I miss the point. ☺. Cheers

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks

Collapse
 
therakesh profile image
Rakesh Mandal 🗯️

A good read Sarah! Thanks for letting me understand the big controversy between these 3 currently we have in our community 😁

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks for reading

Collapse
 
smrgrg profile image
Sameer Gurung

A very good explanation indeed. I was impressed as you did not miss updating of const object properties since most of us might think that anything declared as const cannot be updated :).

Collapse
 
puneet_pandey profile image
Puneet Pandey

Nice to know about var, let and const. Great article!

Collapse
 
jbrennan094 profile image
Joe Brennan

Great explanation, very easy to understand

Collapse
 
rahulrc1995 profile image
Rahul Chandra

Good Post.Thanks.

Collapse
 
ehimze007 profile image
ehimze007

This piece makes sense a 101%. Thank you.

Collapse
 
sabuhiyusifov profile image
Sabuhi

Just started Javascript and learned a lot from this article. Thanks a lot, great explanation!

Collapse
 
mrcamaraderie profile image
Otome Charles Opuoro

Thanks a whole lot Sarah.

Thoroughly enjoyed the article.

It was easy to understand.

Kind regards.

Collapse
 
commandline_ profile image
Okpala Chuks

Nice piece... ES6 all the way!

Collapse
 
sarah_chima profile image
Sarah Chima

Thanks Chuks :)

Collapse
 
vinayp59 profile image
vinayp59

If i declare an array as const variable , Can i update the array?

Collapse
 
sarah_chima profile image
Sarah Chima

While you cannot reassign the array, JavaScript allows you to update it. Personally, I think that defeats the idea of using const. If you want to declare an array that will be updated, it might be more ideal to use let.

Collapse
 
rahulbhatija profile image
rahul bhatija

Thank you Sarah! It helped :)

Collapse
 
jaliph profile image
Akash Chandra

Very well written.. Thanks.. It made this clear

Collapse
 
mengnans profile image
Mengnan Shi

Well explained!

Collapse
 
jkbiggs profile image
Joshua Biggs

Thank you for the article! I didn't know about variable hoisting or why using let and const was preferred over var. Excellent to know!

Collapse
 
delubiod profile image
delubio de paula

I'm glad I found you. No flowery language. Spot on. Thank you Sarah!!!

Collapse
 
paul99337902 profile image
Paul

Excellent article! Thanks!

Collapse
 
slaysoft profile image
Anthony Percivalle

Great article , thank you

Collapse
 
jreckers profile image
jreckers

Super clear explanation -Thanks

Collapse
 
jarf4321 profile image
Jorge Rodríguez

Nice post! It's help me alot to understand the differences!

Collapse
 
praveengovind profile image
Praveen Reddy Govind

Very nice explanation and detailed, Keep it up!

Collapse
 
raissamartinsmenezes profile image
Raissa Martins

Hi, Sarah! you wrote an amazing article, can I translate it to Portuguese to help others here in Brazil who doesn't know English?

Thanks ❤

Collapse
 
sarah_chima profile image
Sarah Chima

Hi Raissa, that will be great! Please go ahead and do so. You can also send a link when you are done. Thank you.

Collapse
 
hninnandarmyint profile image
Hnin N_M

Great Article :) . Thanks so much .

Collapse
 
reigningkingforever profile image
Samuel Oluwadamilola Reigningking

Thanks for this very simple explanation

Collapse
 
arunedathadan profile image
ArunEdathadan

Thanks, but how to use global let variable inside function

Collapse
 
sarah_chima profile image
Sarah Chima

You cannot declare a global variable in a function with let.

Collapse
 
larsolt profile image
Lars

This is great, THANKS!

Collapse
 
daaddychi profile image
Daddy-chi

Very well done! Neat article. Thanks!

Collapse
 
joatorres profile image
JoaTorres

Nice article.

Collapse
 
reach009 profile image
Reach Allen

Well written article, short and sweet summary of these three keywords.

Collapse
 
ramachowdary profile image
rama-chowdary • Edited

Can you please explain me the 3rd point in hoisting of
const

Collapse
 
herichirimwami profile image
herichirimwami • Edited

what is a best way to make a declaration between var, let and const

Collapse
 
pratik4046 profile image
Pratik Agrawal

perfect explanation for var, let and const!!

Collapse
 
ernestph profile image
ErnestPH

Well explained. thanks!

Collapse
 
standoge profile image
Stanley Melgar

Very useful~

Collapse
 
pack1710 profile image
pack1710

This post is still helping people. Thanks!

Collapse
 
cletuskingdom profile image
Cletus Kingdom

Thanks for this.

Collapse
 
sjdz1892 profile image
Sajad Zarsanj

Thanks a lot Sarah, Very helpful.

Collapse
 
tosasilviu profile image
Tosa Silviu

Great article for "var - let - const" explanation. I am just learning Javascript and this guide clears out why I was seeing on other people code, for using the "let" and "const" instead of "var".

Collapse
 
rcindrakumar profile image
IndrakumarRC

Good one, thanks so much!

Collapse
 
staycon64715611 profile image
techstack

Var, Let and Const in Javascript
youtu.be/R45FhbZl5SE

Collapse
 
xemicolon profile image
Light

i now understand the use of let and const. thank you :)

Collapse
 
gudzowski profile image
gudzowski

Thank you for the great article, cleared out a lot for me.
I noticed that "let" are being initialized with undefined though, just like "var".