Table of contents
No headings in the article.
To approach JavaScript scope, we will liken JavaScript to our solar system. The Solar System contains our star: the sun, the eight planets, sub planets, asteroids, comets, etc. Planets are surrounded by their atmosphere and in them, they have moons, clouds etc bounded to them by gravity.
In JavaScript our Solar System is equivalent to our global object (global in Nodejs, Windows object in browser). The Sun, comets, asteroids and planets all exist and can be seen in the solar system. The Sun, comets, asteroids are like variables declared in the app while the planets are like functions.
The planets have an atmosphere which contains moon and cloud which represents arguments and variables defined inside our functions.
Scope defines the accessibility of a variable, where we can see and read a variable from. From earth we can see our moon and cloud and also things outside the atmosphere like the sun, asteroids, etc. but we cannot see into the atmosphere of other planets. Also from space we can see planets, asteroids etc. but we cannot see into other planets and details what they contain.
Likewise in JavaScript, functions, like us in Earth, can look out into the global environment and retrieve values of variables and use them inside our functions, but we cannot retrieve variables from inside other functions.
let carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Also from the global environment as in space, we cannot read and retrieve values that are defined inside functions.
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
NESTED SCOPE
Functions can be defined and declared inside existing functions. As previously described, in our planet earth we have a moon, cloud etc. We also have individual continents and from these continents we can all see the moons, cloud etc. but we cannot see into other continents. Likewise functions declared inside a function can access variables defined in parent function but the opposite cannot happen. Parent functions cannot read variables of child functions.
function myFunction() {
let carName = "Volvo";
function myInnerFunction() {
let innerCarName = "Volvo";
// code here CAN use carName
}
//code here CANNOT use innerCarName
}
DIFFERENCE BETWEEN VAR & LET
ECMAScript 6 introduced the let statement which describes as a local variable just like var.
The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar); // Foo Bar
{
var moo = "Mooo"
let baz = "Bazz";
console.log(moo, baz); // Mooo Bazz
}
console.log(moo); // Mooo
console.log(baz); // ReferenceError
}