Ufuk's Blog

Var, let and const

☕️ 1 min read

With ES6, we now have three options to define a variable. It would be somehow confusing if you are just getting started to learn JavaScript. I assume that you already use var. Let’s take a closer look at the new ones and see the differences.

Let

It looks like do the same job with var but there is a difference: we can re-define a variable with var but let does not let us to do that :) That is a feature that nice to have especially when developing larger applications. We can’t re-define but we can re-assign a value to the variable which is defined with let.

// "age" is 22 now
var age = 22;

// now it is 23!
var age = 23;

// "birthYear" is 1996 now
let birthYear = 1996;

// we can't do the following!
let birthYear = 1997;

// but we can do this
birthYear = 1997;

Const

This is the most preferable one among the developers. If you define a variable with const you can’t re-define another variable with the same name and also you can’t re-assign a value to that.

// "name" is "Ufuk" and it always be!
const name = 'Ufuk';

// we can't do this!
name = 'John';

I personally try to use const more often. It gives us a little bit more consistency.