Var, Let and Const

Var, Let and Const

Datatypes declaration and its rules in JavaScript

Confused about when to use let, var, or const? Get ready for a clarity boost as we dissect these three keywords and their roles in JavaScript.

Syntax

Let's understand each keyword's syntax:

var name; //decalring using var
let lastname; //decalring using let


const accountId      // ❌SyntaxError: Missing initializer in const declaration

// πŸ‘‰ You should initialize the variable with a value at the time of declaration in const:
const accountId = '123456' // decalring using const

Rules of writing variables(also known as Identifiers):

  1. The name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.

  2. After first letter we can use digits (0 to 9), for example value1.

  3. JavaScript variables are case sensitive, for example x and X are different variables.

  4. Reserved keywords cannot be used as variable names since they have special meanings within the language. For example, you cannot use words like if, function, or let as variable names.

let fullName = "Johnathan Wick"   //valid
var user01Id = "123456"           //valid

var *name = "Dhiraj"            //❌  Invalid 
let 01user = "Spiderman"        //❌  Invalid

Here are a few key points that need to know

  1. Reassign & Redeclaration

// πŸ‘‰ < -------------------- VAR ------------------------ > 
var count = 5;
console.log(count); // Output: 5

// 🧷 Redeclaration of variable with same name is Valid in var
var count = 10;       
console.log(count); // Output: 10 

// 🧷 Reassign of variable is valid in var
count = 15;
console.log(count); //Output: 15



// πŸ‘‰ < -------------------- Let ------------------------ > 
let isVerified = false
console.log(isVeried) //  Output: false

//Redeclaration is not allowed
let isVerified = true    // ❌ SyntaxError: Identifier 'isVerified' has already been declared

//βœ… Reassigning is allowed
isVerified = true 
console.log(isVerified); //Output: true



// πŸ‘‰ < -------------------- CONST------------------------ > 
const isAdmin = false

//Redeclaration is not allowed 
const isAdmin = true         //❌ SyntaxError: Identifier 'isAdmin' has already been declared

//Reassign of varaiable is not valid 
isAdmin = true       //❌ Uncaught TypeError: Assignment to constant variable.

console.log(isAdmin);  //Output: false
  1. Scope of variable

    Understanding scoping is important for proper variable management and preventing unintended variable access or conflicts in your JavaScript code.

function myFunction() {
  let x = 10;
  var abc = 5;
  if (true) {
    let y = 20;
    const z = 30;
    console.log(abc);  //Output: 5
    console.log(x); // Output: 10
    console.log(y); // Output: 20
    console.log(z); // Output: 30
  }
  console.log(abc);  //Output: 5
  console.log(x); // Output: 10
  console.log(y); // Output: ReferenceError: y is not defined
  console.log(z); // Output: ReferenceError: z is not defined
}

myFunction();
console.log(abc);  //Output: ReferenceError: abc is not defined
console.log(x); // Output: ReferenceError: x is not defined
console.log(y); // Output: ReferenceError: y is not defined
console.log(z); // Output: ReferenceError: z is not defined

Block Scope : In this example, the variables x, y, and z are declared using let and const. They are block-scoped, meaning they are accessible only within the block where they are declared. The if statement creates a block scope, so y and z are accessible only inside the if block. Trying to access them outside of the block or in the global scope results in a ReferenceError.
Functional Scope: But if you observe abc is declared using var it accessed inside function block. The if statement does not create a new scope, so the variables declared inside it are still accessible outside of the if block, this is called functional scope. Trying to access abc outside of the block or in the global scope results in a ReferenceError.

Did you find this article valuable?

Support Dhiraj Inchalkaranji by becoming a sponsor. Any amount is appreciated!

Β