Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Sarah Chima
Sarah Chima

Posted on • Edited on

     

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

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 and have started using these features. While this assumption might be true, it's still possible that some of these features remain a mystery to some.

One of the features that came with ES6 is addition oflet andconst which can be used for variable declaration. The question now is, what makes them different from our good ol'var which has been in use? If you are still not clear about this, this article is for you.

In this article,var,let andconst will be discussed with respect to their scope, use and hoisting. As you read, take note of the differences between them I'll point out.

VAR

Before the advent of ES6,var declarations ruled as King. There are issues associated with variables declared withvar though. That is why it was necessary for new ways to declare variables to emerge. First though, let us get to understandvar more before we discuss one of such issues.

Scope ofvar

Scope essentially means where these variables are available for use.var declarations are globally scoped or function/locally scoped. It is globally scoped when avar variable is declared outside a function. This means that any variable that is declared withvar outside a function block is available for use in the whole window.var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.
To understand further, look at the example below.

vargreeter="hey hi";functionnewFunction(){varhello="hello";}
Enter fullscreen modeExit fullscreen mode

Here,greeter is globally scoped because it exists outside a function whilehello is function scoped. So we cannot access the variablehello outside of a function. So if we do this:

vartester="hey hi";functionnewFunction(){varhello="hello";}console.log(hello);// error: hello is not defined
Enter fullscreen modeExit fullscreen mode

We'll get an error which is as a result ofhello not being available outside the function.

var variables can be re-declared and updated

That means that we can do this within the same scope and won't get an error.

vargreeter="hey hi";vargreeter="say Hello instead";
Enter fullscreen modeExit fullscreen mode

and this also

vargreeter="hey hi";greeter="say Hello instead";
Enter fullscreen modeExit fullscreen mode

Hoisting ofvar

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. What this means is that if we do this:

console.log(greeter);vargreeter="say hello"
Enter fullscreen modeExit fullscreen mode

it is interpreted as this

vargreeter;console.log(greeter);//greeter is undefinedgreeter="say hello"
Enter fullscreen modeExit fullscreen mode

Sovar variables are hoisted to the top of its scope and initialized with a value of undefined.

Problem withvar

There's a weakness that comes withvar. I'll use the example below to explain this.

vargreeter="hey hi";vartimes=4;if(times>3){vargreeter="say Hello instead";}console.log(greeter)//"say Hello instead"
Enter fullscreen modeExit fullscreen mode

So, sincetimes > 3 returns true,greeter is redefined to"say Hello instead". While this is not a problem if you knowingly wantgreeter to be redefined, it becomes a problem when you do not realize that a variablegreeter has already been defined before.
If you have usegreeter in other parts of your code, you might be surprised at the output you might get. This might cause a lot of bugs in your code. This is why thelet andconst is necessary.

LET

let is preferred for variable declaration now. It's no surprise as it comes as an improvement to thevar declarations. It also solves this problem that was raised in the last subheading. Let's consider why this is so.

let is block scoped

A block is chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block. So a variable declared in a block with thelet is only available for use within that block. Let me explain this with an example.

letgreeting="say Hi";lettimes=4;if(times>3){lethello="say Hello instead";console.log(hello);//"say Hello instead"}console.log(hello)// hello is not defined
Enter fullscreen modeExit fullscreen mode

We see that usinghello outside its block(the curly braces where it was defined) returns an error. This is becauselet variables are block scoped .

let can be updated but not re-declared.

Just likevar, a variable declared withlet can be updated within its scope. Unlikevar, alet variable cannot be re-declared within its scope. So while this will work,

letgreeting="say Hi";greeting="say Hello instead";
Enter fullscreen modeExit fullscreen mode

this will return an error.

letgreeting="say Hi";letgreeting="say Hello instead";//error: Identifier 'greeting' has already been declared
Enter fullscreen modeExit fullscreen mode

However, if the same variable is defined in different scopes, there will be no error.

letgreeting="say Hi";if(true){letgreeting="say Hello instead";console.log(greeting);//"say Hello instead"}console.log(greeting);//"say Hi"
Enter fullscreen modeExit fullscreen mode

Why is there no error? This is because both instances are treated as different variables since they have different scopes.

This fact makeslet a better choice thanvar. When usinglet, you don't have to bother if you have used a name for a variable before as a variable exists only within its scope. Also, since a variable cannot be declared more than once within a scope, then the problem discussed earlier that occurs withvar does not occur.

Hoisting oflet
Just likevar,let declarations are hoisted to the top. Unlikevar which is initialized asundefined, thelet keyword is not initialized. So if you try to use alet variable before declaration, you'll get aReference Error.

CONST

Variables declared with theconst maintain constant values.const declarations share some similarities withlet declarations.

const declarations are block scoped

Likelet declarations,const declarations can only be accessed within the block it was declared.

const cannot be updated or re-declared

This means that the value of a variable declared withconst remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable withconst, we can neither do this

constgreeting="say Hi";greeting="say Hello instead";//error : Assignment to constant variable.
Enter fullscreen modeExit fullscreen mode

nor this

constgreeting="say Hi";constgreeting="say Hello instead";//error : Identifier 'greeting' has already been declared
Enter fullscreen modeExit fullscreen mode

Every const declaration therefore, must be initialized at the time of declaration.
This behavior is somehow different when it comes to objects declared withconst. While aconst object cannot be updated, the properties of this objects can be updated. Therefore, if we declare aconst object as this

constgreeting={message:"say Hi",times:4}
Enter fullscreen modeExit fullscreen mode

while we cannot do this

constgreeting={words:"Hello",number:"five"}//error :  Assignment to constant variable.
Enter fullscreen modeExit fullscreen mode

we can do this

greeting.message="say Hello instead";
Enter fullscreen modeExit fullscreen mode

This will update the value ofgreeting.message without returning errors.

Hoisting ofconst

Just likelet,const declarations are hoisted to the top but are not initialized.

So just in case, you missed the differences, here they are :

  1. var declarations are globally scoped or function scoped whilelet andconst are block scoped.

  2. var variables can be updated and re-declared within its scope;let variables can be updated but not re-declared;const variables can neither be updated nor re-declared.

  3. They are all hoisted to the top of their scope but whilevarvariables are initialized withundefined,let andconst variables are not initialized.

  4. Whilevar andlet can be declared without being initialized,const must be initialized during declaration.

Got any question or addition? please leave a comment.

Thank you for reading :)

Top comments(99)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
abhijeetckar92 profile image
abhijeetckar92
  • Joined
• Edited on• 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!

CollapseExpand
 
abdushaker profile image
Abdu Shaker
  • Joined

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.

CollapseExpand
 
bkmillanzi profile image
Bkmillanzi
  • Location
    Dar es Salaam, Tanzania
  • Work
    Founder at SOSHUB Group
  • Joined

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

CollapseExpand
 
sarah_chima profile image
Sarah Chima
Software engineer, Tech educator
  • Location
    Sweden
  • Joined

thank you

CollapseExpand
 
ramachowdary profile image
rama-chowdary
I like to look into examples which is clearle explained.
  • Location
    Hyderabad
  • Work
    Front end developer
  • Joined

Yeah

CollapseExpand
 
curiousconfuseddev profile image
Ansh
Hey devs, Myself Ansh I am a JS, PHP developer and coming soon with multiple techs. I am interested in web development
  • Location
    Pune
  • Work
    Software Developer at Eastern Enterprise
  • Joined

It's updated now. Thanks for notifying

CollapseExpand
 
domin profile image
Dominic Sears
Laravel Developer, TALL (TailwindCSS, Alpine.JS, Laravel, Livewire), UI/UX Design, disciple, and love anime
  • Education
    Chaffey College
  • Work
    International Christian Churches, Inc.
  • Joined

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

CollapseExpand
 
sarah_chima profile image
Sarah Chima
Software engineer, Tech educator
  • Location
    Sweden
  • Joined

I'm glad it did.

CollapseExpand
 
jeansberg profile image
Jens Genberg
Software engineer with a passion for game development.
  • Email
  • Location
    Finland
  • Education
    B.Sc Information Technology
  • Work
    Software Engineer at Greenbyte
  • Joined

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

CollapseExpand
 
sarah_chima profile image
Sarah Chima
Software engineer, Tech educator
  • Location
    Sweden
  • Joined

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

CollapseExpand
 
itayko profile image
itayko
  • Joined

Thank for a great article

Error still exists in the article..

CollapseExpand
 
ashbrandn profile image
Ashley Brandon
  • Joined

Why should var be avoided?

CollapseExpand
 
sgmallon profile image
Scott Mallon
Software Developer. I love React JS.
  • Education
    B.S. Computer Science
  • Work
    Software Engineer
  • Joined
• Edited on• 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
aid worker turned web developer
  • Location
    Toronto
  • Joined

This was incredibly helpful, and a great TLDR!

CollapseExpand
 
mushin108 profile image
Mushin108
  • Location
    Long Beach, CA
  • Joined

"Variable shadowing"

CollapseExpand
 
olawanle_joel profile image
Joel Olawanle
Frontend Engineer and Technical writer. I love and write more about JS💛
  • Location
    Nigeria
  • Pronouns
    He/Him
  • Work
    Technical Editor @ Kinsta
  • Joined
• Edited on• 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 modeExit 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 modeExit fullscreen mode

But this could easily be avoided by making use ofObject.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 modeExit fullscreen mode

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

CollapseExpand
 
avrani profile image
Ariel
  • Joined

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 inw3schools.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

CollapseExpand
 
sobhardwaj profile image
Siddharath shankar bhardwaj
  • Joined

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 ??

CollapseExpand
 
mohammedyehia profile image
Mohammed
  • Joined

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

CollapseExpand
 
wolf00bomber profile image
Wolf00Bomber
  • Joined

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.

CollapseExpand
 
kramffud profile image
Mark Duff
Developing since before the internet; before Windows. 'Bout it.
  • Location
    Lone Star State
  • Work
    Sr. Architect at Web Techsmiths
  • Joined

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.

CollapseExpand
 
sarah_chima profile image
Sarah Chima
Software engineer, Tech educator
  • Location
    Sweden
  • Joined

Thanks for the kind words, I really appreciate it.

CollapseExpand
 
gamebecks profile image
gamebecks
  • Joined

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?

CollapseExpand
 
nicksu86 profile image
NickSu86
  • Joined

Thank you for your post, I am a newbie to Nodejs and quite confusing on when to uselet,const orvar. As I saw some require a module withvar while some withconst, could you advise which is better when requiring a module? After reading your post, I thinkconst 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 thanscope, thank you

CollapseExpand
 
full_stackgeek profile image
Ayush Jain
Software Engineer | AWS Certified Cloud PractitionerI usually share my knowledge at:https://topmate.io/ayush_jain56/
  • Joined

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

Some comments may only be visible to logged-in visitors.Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software engineer, Tech educator
  • Location
    Sweden
  • Joined

More fromSarah Chima

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp