In JavaScript, variables and methods are declared using both let
and var
. However, the let
keyword is block scoped, whereas the var keyword is function scoped, which is the key distinction between the two JS keywords. Additionally, hoisting happens in var, but it doesn't happen in let
.
A variable declared with the var
keyword can be used anywhere within a function. For instance,
// variable x cannot be used here
function program() {
var x = 'JavaScript';
console.log(x);
}
// variable x cannot be used here
program(); // JavaScript
Output:
JavaScript
In the code above, the variable a
is declared with var
. Within the function greet, the variable a
can be used wherever you like.
Only within a code block can we access a variable declared with let
. For instance,
function program() {
let x = 'JavaScript';
// variable y can't be used here
if(a == 'JavaScript'){
// variable y can be used here
let y = 'is amazing';
console.log(x + ' ' + y);
}
// variable y cannot be used here
console.log(x + ' ' + y); // error
}
// variable x cannot be used here
program();
Output
JavaScript is amazing
Uncaught ReferenceError: y is not defined
The variable x is declared inside the function in the program above, and it can be accessed from anywhere inside the function (‘a’ becomes function scoped).
However, the if block statement contains a declaration of the variable y. Block-scoped and only accessible from within the if block, y
will be.
Consequently, an error occurs when you attempt to access y outside of the if block (as shown above in the program). It should be noted that a function's declared variables will have scope for both var
and let
.
A variable that has been declared using the keyword var
can also be declared again. For example,
var a = 15; // 15
var a = 13; // 13
A variable that has been declared with the let/code> keyword cannot be redeclared within the same block or same scope. For example,
let a = 15;
let a = 13; // error