DEV Community

Reggie Peterson
Reggie Peterson

Posted on

ES6: Const & Let

~View the original post here at jayess.lifesandwich.co~

Who uses var? Not you hopefully. ES6 (ES2015) killed it for the better. It's replaced by two new variable assignment keywords; Const & Let — they work a little bit differently than var.


Const: Your go-to 99% of the time.

Let: Use it only when needed.


So what's the difference? Why are they so much better than var?

The answer is that Const & Let are block scoped vs var which is function scoped.


Block Scoped: only exist between a pair of curly braces { //code }

Function scoped: only exists within the current function.


The primary difference here is that naming a variable using const or let in an if statement, or a loop will basically hold that variable within it and will not allow it outside.

so this:

if(true) {
var x = 2;
}
console.log(x)

logs 2,
but this:

if(1 === 1) {
const y = 2;
}
console.log(y)

throws an error.

This is because x, created with var, doesn't care about the if statement { }, but const (and let) does.

This is a good thing, because it means if you accidentally name two variables the same, you won't get unexpected behavior, since a variable inside an if/ function/ loop will be completely different than one (named the exact same thing) outside of those { }. It helps avoid naming collisions.

Const vs Let

let is the same as var, aside from the block scope thing we just talked about.

const, however, is short for constant, and means that you can't reassign it.

so:

let a = 1
a = 2

is cool.
but this:

const b = 1
b = 2

is a no go

You also have to initialize const with a value:

let c;
c = 3

is fine
but:

const d;
d = 4;

is not. (it'll error on that first line)

This is good because it means you can't accidentally reassign a value (although you can mutate arrays and objects via push, pop, and such).

//RECAP

Var isn't great because it's function scoped and reassignable. Which is theoretically fine. but it opens the door for bad juju (namespace collision, unexpected values)

const and let are block scoped, and const is also not reassignable, which is why const should be used all of the time, except when you for sure need to reassign (like when incrementing in a loop).

Ditching var is a simple step to future proof your code and reduce bugs, and your users will thank you for it.


~View the original post here at jayess.lifesandwich.co~

Top comments (2)

Collapse
 
bananabrann profile image
Lee • Edited

const VS let is a fun one. I think both have their reasonings behind it, but I believe it all depends on preference and/or the project.

Why do you choose to use const over let?

Collapse
 
pedro2555 profile image
Pedro Rodrigues

mood. their pointless.