var, const and let in JavaScript

var, const and let in JavaScript

·

3 min read

Ever wondered why and when to use var, const and let in JavaScript? Let's find out.

In other programming languages like Python decimal parts of a number are called Integers and the fractional part is called Float. However, in JavaScript, all numbers are just a number type. Basically, JavaScript doesn't have any floats, integers, etc. Everything is a number.

Let's define a JavaScript variable that has a value of 20 stored in it.

const number = 20 //stores 20 inside number

we can do the same thing like this aswell

let number = 20 and var number = 20

So you might have guessed that var, const and let all do the same thing i.e define a variable. Now, you might be wondering if they do the same thing why do we have 3 of them? Why not only var or const or let?

var, const and let do the same thing but act very differently technically. Amongst these three variable declarations, var is the oldest. It was the only way to declare variables before the introduction of let and const. The var keyword has been a part of JavaScript since its inception which is 1995 and let was introduced in ES6 in 2015 and const was also introduced in ES6 but was added later in the language.

'const' vs 'let'

The difference between const and let is that let can be updated later where as const cannot be updated later. Let's look at the examples

let name = 'john';

console.log(name);

//prints john

name = 'som';

console.log(name);

//prints: som

Now, let's do the same thing but with const

const name = 'john';

console.log(name);

//prints john

name = 'som';

console.log(name)

//TypeError: Assignment to constant variable.

'const' vs 'let': who wins?

Generally, it is good practice to use const if you don't plan to change the name later on. You can use let if you plan to change the name later on but I will suggest creating new variables instead of overwriting them.

what about 'var'?

Well, var has been there for a very long time and is kinda a piece of legacy code now. var acts the same as const and let but it does something weird as well.

var works with function scopes but not with block scopes. Let's take a look

function printX(shouldSet) {
  if (shouldSet){
    var x = 2
  }
  console.log(x);
  // Prints: 2
}
printX(true)
function printX(shouldSet) {
  if (shouldSet){
    let x = 2
  }
  console.log(x);
  // ReferenceError: x is not defined
}
printX(true)

Here, the let keyword makes more sense because it treats the block scopes just like function scopes and every other programming language does that too.

So, in conclusion, always use let and const and never var.