Scope in JavaScript

Scope in JavaScript

·

2 min read

Due to my high irritability tendency to articles with long unrelated introductions whose purpose seem to not be beyond simply increasing the article's word count, I'll dive straight to the point.

Scope in programming refers to the access level of an identifier (or variable, of course). You would fail in trying to attempt accessing a variable beyond its scope. Beyond are the different types of scopes in JavaScript.

Global scope.

Creating a variable outside and above any functions is usually enough for it to be of global scope, but also, variables defined without any keywords are assigned a global scope. This is of course bad practice, but it's possible and might not be allowed on some JavaScript frameworks or libraries.

app.js.png

For the second part where we saw what the "bad way" looks like, we'd notice that the function had to be called before the variable can be used outside the function. This is because JavaScript has no idea what the variable is supposed to mean until we show the instantiation of the variable.

Functional scope.

The var keyword is used to create variables of functional scope. When variables are created using the var keyword, the variables declarations float all the way to the top of the closest enclosing function during interpretation. This is called hoisting. This means that you can use a variable before it is declared. Also, you have the liberty of declaring a single variable multiple times because when they float to the top, similar declarations cancel each other out.

app.js (1).png

The above code would run perfectly of course, because during interpretation, this is equivalent to:

app.js (2).png

Block scope.

Variables declared with block scope would only be accessible within the block they were created. For example, if statements, switch statements, loops and function blocks too. The let keyword is what is being used to declare variables with block scope.

app.js (3).png

Below, we'll notice that unlike declaration by instantiation we talked about in the block scope section, running a function before trying to access a block-scoped variable doesn't make it accessible outside the function.

app.js (54.png