JavaScript var, let and const

JavaScript var, let and const

Table of contents-

  • Introduction

  • var

  • let

  • const

Introduction

Everyone knows JavaScript as one of the most popular web design languages, which makes our web page attractive and dynamic.

Let's see about Javascript variable declaration keywords-

1. var

var is the oldest keyword used in javascript but now in modern Javascript mostly we try to avoid it, why? Behind it is a reason-

When we use var for any variable it makes that variable globally accessible, you may take it as a feature of var or disadvantage too..What happens when someone changes the value of the var variable? For this reason, we try to avoid it.

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);

}

console.log(x);

// output will be the 2,2 because we redecalred it.
  1. let

This keyword comes to avoid the disadvantage of var, it provides block-level access.

The scope of a let variable is only block-scoped. It can’t be accessible outside the particular block ({block}) means no other part of the code can change it.

let a = 10
if (true) {
    let a = 9
    console.log(a) // It prints 9 & cant use outside the block
}
console.log(a) // It prints 10
  1. const

This is also a block-level keyword, but a restriction you must have to initialize it to use.

And also after the initialization you cant update it anywhere else. const keyword has its specific use.

const a = {
    value1: 1,
    value2: 9
}

// It is allowed
a.value3 = 3

// It is not allowed
a = { 
    b: 10,
    value2: 9
}

Hope this article may be helpful to everyone.