In the early years of JavaScript, they introduced the only variable declaration keyword "var" that can make you declare a variable.
1- var
var is global-scoped or function-scoped, but what does that mean?
- global scope means that the variable is available to be used at any level in the code after the line where it is declared. Ex:
var height = 20;
console.log(height); // output: 20;
if (true) {
var width = 20;
}
console.log(width); // output: 20;
function-scoped because when we declare a variable inside a function we can't access it out of that function.
function testVar() {
var test = "Tested";
}
console.log(test); // ReferenceError: test is not defined
- Can be reassigned.
var height = 20;
height = 0;
console.log(height) // output: 0
- Can be redeclared.
var height = 20;
var height = 10;
console.log(height) // output: 10
It is important to note that developers abandoned using var keyword due to its global scope and re-declaration behavior since it can be prone to errors. imagine you are writing 200 lines of code and at line 201 you decide to declare a variable that you have already declared but you forgot that you have this variable already initialized above, you need some error message to tell you that you already have this variable initialized. and also to reduce errors you shouldn't access a variable out of its scope.
2- let
Let is block-scoped, that means it will be available to use only at its scope but not in any outer scopes.
Ex:
let height = 20;
console.log(height); // output: 20;
if (true) {
let width = 20;
}
console.log(width); // ReferenceError: width is not defined
function testVar() {
let test = "Tested";
}
console.log(test); // ReferenceError: test is not defined
- Can be reassigned, but can't be redeclared.
let height = 20;
height = 0;
console.log(height) // output: 0
3- const
same as let keyword it is block-scoped but can't be reassigned or redeclared, as the name suggests it is constant and can't be changed.
Ex:
let height = 20;
console.log(height);
// output: 20;
if (true) {
let width = 20;
}
console.log(width);
ReferenceError: width is not defined
function testVar() {
let test = "Tested";
}
console.log(test);
ReferenceError: test is not defined
Top comments (0)