What is the difference between var and let in Javascript
In JavaScript, both var
and let
are used to declare variables.
The let
keyword was introduced in ECMAScript 6 (ES6) as an improvement over the var
keyword.
What is the difference between var and let in Javascript #
The main difference between var
and let
is that.
var
has function-level scoping.let
has block-level scoping.
To put it simply, let
has the same behavior as most modern programming languages, and I think it is recommended to use in today's JavaScript development.
Here is a longer answer.
- A variable declared using
var
is accessible throughout the entire function in which it is declared. You can access it even before the declaration. - A variable declared using
let
is accessible within the block they are declared in. This is the behavior you probably expected.
Here is an example of let
and var
.
function varExample() {
console.log(x);
// print undefined
if (true) {
var x = 2;
console.log(x);
// print 2
}
console.log(x);
// print 2
}
function letExample() {
// x is not known here
// You will get "ReferenceError: x is not defined" error
// If you trying to reference x
if (true) {
let x = 2;
console.log(x);
//print 2
}
// x is not known here
}
In the first example using var
, the x
is declared inside an if
block, but we can access its value at the beginning where the value is undefined
and after the if
block where the value is 2
.
In the second example using let
, the x
can only be used within the if
block. Trying to access it elsewhere would cause a "ReferenceError: x is not defined" error. This is the same behavior as most modern programming languages.