What Are JavaScript’s Var, Let, and Const Keywords?

A variable in JavaScript can be declared using three keywords.

  • var
  • let
  • const

1.Var

  • It is the most traditional method of declaring a variable.
  • We can reassign the variable’s value by using the var keyword.
  • It is also permissible to declare a variable name with the same name.
  • The var keyword has a global/function scope.
  • Because its default value is “undefined,” it can be accessed without being initialized.
var Data='Apple';
console.log(Data); // Apple
var Data='Orange';
console.log(Data);  // Orange

2.Let

  • It is possible to reassign.
  • However, defining a variable with the same name is not permitted.
  • The let keyword’s scope is block scope.
  • It cannot be accessed without first being initialised, as it produces an error.
let data='Apple';
console.log(data); // Apple
let data='Orange'; // Error
data= 'Avocado' // Avocado
console.log(data);

3.Const

  • Re-assignment is not permitted.
  • Cannot be defined without first being initialised.
  • Declaring a variable with the same name is likewise not permitted.
  • The const keyword has block scope as well.
  • It cannot be accessed without first being declared, and it cannot be proclaimed without first being accessed.
const data;  // Error
const value= 'Avocado';
const value= 'Apple'; // Error
value= 'Orange'; // Error

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories