The var statement is used to declare a variable in JavaScript. A variable declared with the var keyword is defined throughout the program.
var greeter = "hey hi"; var times = 5; if (times > 3) { var greeter = "Say Hello rookienerd"; } console.log(greeter) //Output: Say Hello rookienerd
The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error. A variable declared with the let keyword is limited to the block-scoped only.
let greeter = "hey hi"; let times = 5; if (times > 3) { let hello = "Say Hello rookienerd"; console.log(hello) // Output: Say Hello rookienerd } console.log(hello) // Compile error: greeter is not defined
The above code snippet throws an error because the variable "hello" is not defined globally.
SN | var | let |
---|---|---|
1. | The var keyword was introduced with JavaScript. | The let keyword was added in ES6 (ES 2015) version of JavaScript. |
2. | It has global scope. | It is limited to block scope. |
3. | It can be declared globally and can be accessed globally. | It can be declared globally but cannot be accessed globally. |
4. | Variable declared with var keyword can be re-declared and updated in the same scope. Example: function varGreeter(){ var a = 10; var a = 20; //a is replaced console.log(a); } varGreeter(); |
Variable declared with let keyword can be updated but not re-declared. Example: function varGreeter(){ let a = 10; let a = 20; //SyntaxError: //Identifier 'a' has already been declared console.log(a); } varGreeter(); |
5. | It is hoisted. Example: { console.log(c); // undefined. //Due to hoisting var c = 2; } |
It is not hoisted. Example: { console.log(b); // ReferenceError: //b is not defined let b = 3; } |