DEV Community

Visakh Vijayan
Visakh Vijayan

Posted on

let & const

ES6 introduced two new alternatives to var keyword namely let and const.

var allows you to define the same variable over and over again without any errors.

var x = 10;
var x = 10; // Doesn't throw up an error

Enter fullscreen mode Exit fullscreen mode

This might lead to accidentaly changing the values of a variable.

However, this is not the case with let. If you try to do the same thing with let, it will throw up an error.

let x = 10;
let x = 10; // Duplicate declaration error.

Enter fullscreen mode Exit fullscreen mode

const on the other hand is used when you want to create variable that won't change it's value ever.

const x = 10;
x = 12; // Cannot reassign ever.

Enter fullscreen mode Exit fullscreen mode

Function and Block scoping

While var,let and const have function level scoping, let and const go a step further. They allow block level scoping too.

var x = 10;
let x1 = 10;

if (1)
   var y = 10;
   let y1 = 10;

console.log(y); // Y is available over here.
console.log(y1); // Y is not available over here.

Enter fullscreen mode Exit fullscreen mode

Next: Coming soon

Discussion (2)

ceckenrode profile image
Christian Eckenrode

Awesome write up!

Just want to point out that if you have an array or an object declared with const, you can still modify them since they’ll still be pointing to the same value in memory. Example:

This is okay!

const person = {} = Christian

const hobbies = [playing guitar]

But doing either of these will result in an error

const person = {}
person = { name: Visakh }

const hobbies = []
hobbies = [coding]

So you can modify arrays an objects, but you can reassign them altogether (by resetting their value with the equals sign)

const in JavaScript doesn’t mean constant value, it means constant reference. See here.

You’re 100% correct when it comes to other primitive types though 🙂

qzsg profile image

If an array or an object is assigned to a const, note that it's contents can still be modified