In JavaScript, developers can declare a variable using 3 keywords.
- var
- let
- const
1. var
- It is the oldest way to declare a variable.
- Using the var keyword we can re-assign the value to the variable.
- Declaring a variable name with the same name is also allowed.
- The scope of the var keyword is global/function scope.
- It can be accessed without initialization as its default value is “undefined”.
var myname='xxx';
console.log(myname); // xxx
var myname='yyy'; // yyy
console.log(myname);
2. let
- Re-assigning is allowed.
- But, declaring a variable with the same name is not allowed.
- The scope of the let keyword is block scope.
- It cannot be accessed without initialization, as it returns an error.
let yourName='xxx';
console.log(yourName); // xxx
let yourName='yyy'; // Error
yourName = 'zzz' // zzz
console.log(yourName);
3. const
- Re-assigning is not allowed.
- Cannot be declared without initialization.
- Declaring a variable name with the same is also not allowed.
- The scope of the const keyword is also block scope.
- It cannot be accessed without initialization, as it cannot be declared without initialization.
const testName; // Error
const testNames = 'xyz';
const testNames = 'zyx'; // Error
testNames = 'zyxx'; // Error