Introduction
Scope, is, just scope. In other words scope is the visibility of a variable within a { }
delimited block of code and where it is initially declared. That’s what scope really is.
Scope determines the accessibility (and visibility) of variables.
Modern JavaScript has 3 types of scope:
- Block scope
- Function scope
- Global scope
In short variable(s) declared inside a block of code delimited by curly braces {}
are not visible outside that “scope” as from ES6.
Global Scope
The var
keyword and global scope pollution
The var
keyword (used alot in pre-ES6 days) introduces a global scope when used to declare a variable.
so:
{
var myDub = "dubstep on bike"
}
console.log(myDub) // prints "dubstep on bike"
// can be used here!
Variable myDub
“leaks” to the outerscope (global scope) and can be accessed outside the scope declared in. This pollutes the global scope since it is accessible outside, other parts of the program can still have access to read and modify the variable.
Block Scope
let
and const
keywords
ES6 introduced let
and const
keywords for declaring variables in non-global scoped manner.
let
keyword introduces a block scope variable. This means the variable can be accessed within the {}
they are declared in an nowhere else, kinda great right?
const
does something similar but useful when variable needs not to change within the block scope it was declared in, hence can not be reassigned.
{
let myDub = 'dubstep on bike'
}
console.log(myDub) // prints "undefined"
// myDub can not be used here!
Function scope
Function scope limits visibility/accessibility of a variable to the function expression declared in:
function myDubDetails {
let dubVersion = 'v2020'
// dubVersion is visible inside this function body and not anywhere else
}
Introduce global Scope using either let
, const
Intentionally introducing a global scope
A global scope can be used to introduced to create global variables. For example declaring the variables at top level of program makes the accessible anywhere inside the program:
let myDub = 'dubstep on bike'
let dubEdition = '2020 Edition'
const printDubEdition= () => {
// myDub and dubEdition are accessible here and anywhere else!
console.log(`${myDub} edition: ${dubEdition}`) // prints dubstep on bike edition: 2020 Edition
}
// myDub, dubEdition accessibe and modifiable anywhere
Never introduce global variables anywhere inside your code unless you intentionally want to. var
is deprecated and you would rarely see it in modern codebases. Strive to use let
and const
whenever possible when working with modern JavaScript and beyond.