28
loading...
This website collects cookies to deliver better user experience
const myFunction = () => {
var x = "this is declared inside myFunction"
console.log(x)
}
myFunction()
//this is declared inside myFunction
console.log(x)
//error: Uncaught ReferenceError: x is not defined
var
variables exist since way before block scope was introduced, so they have no block scope. var declarations are either function-scoped or global-scoped, which were the only two scope types available before ES6.var
declarations will see through blocks and take the scope of the parent element. For example:if (true) {
var x = "this is inside a block"
}
console.log(x)
//this is inside a block (is it?)
var
to declare it, and the block itself wasn't inside a function.const myOtherFunction = () => {
if (true) {
var x = "this is inside a block"
}
console.log(x)
}
myOtherFunction()
//this is inside a block
console.log(x)
//error: Uncaught ReferenceError: x is not defined
var
works. Let's see what's the difference with let.let
was introduced in ES6 along with const
as a new way to declare variables.let
works similarly to var
, but this one is block-scoped.if (true) {
let x = "this is inside a block"
console.log(x)
//this is inside a block (now it is)
}
console.log(x)
//error: Uncaught ReferenceError: x is not defined
let
declaration helped us keep it inside the block.var
can lead to that without you even noticing.let
is used almost everywhere, and it does have its benefits 👌. It can particularly help you avoid bugs in your applications caused by the use of global variables.