Scope determines the accessibility (visibility) of variables. In JavaScript there are three types of scope: Block scope, Function scope, and Global scope.
Before ES6 (2015), JavaScript had only Global Scope and Function Scope. ES6 introduced
let and const, which provide
Block Scope. Variables declared inside a {}
block cannot be accessed from outside the block.
{
let x = 2;
}
// x can NOT be used here
Variables defined inside a function are not accessible (visible) from
outside the function. Variables declared with var, let, and
const are very similar when declared inside a function.
function myFunction() {
let carName = "Volvo"; // Local Scope
}
// carName can NOT be used here
A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it.
let carName = "Volvo"; // Global Scope
function myFunction() {
// code here can use carName
}
window object in browsers
"use strict"; prevents accidentally creating global variables