Join us
@ayushtibra ă» Jan 30,2022 ă» 4 min read ă» 1156 views ă» Originally posted on medium.com
JavaScript is weird, right? A lot of times, developers see an unexpected behavior in their code and they just want to tear their hair out. In this article, I am covering the two concepts that will help you understand those weird behaviors.
What is Scope?
Scope in JavaScript refers to the accessibility of variables, functions, and objects during runtime.
In JavaScript, there are three types of scopes:
Global scope is the outermost scope, a variable is in global scope if itâs declared outside of a block.
window
and document
are global variables provided by the browser.
Variables inside the global scope can be accessed and altered in any other scope.
Any variables or functions declared inside a function have local/functional scope, which means that they can be accessed within the function and not outside of it.
Block scope tells us that any variable declared inside a block {}, can be accessed only inside that block and cannot be accessed outside of it.
Block scope is related to variables declared using let
and const
only, var
do not have block scope.
Block statements like if
and switch
conditions or for
and while
loops create a block-level scope.
Hoisting:
When executing a JavaScript code, the JavaScript engine goes through two phases:
So, hoisting is a mechanism that the JavaScript engine moves all the variables, functions declaration
to the top of their scope, before the execution of the code. It allows functions and variables to be used in code before they are declared.
Take a look at the code below and guess what happens when we execute this:-
Every developer coming from any programming language will expect the output to be: ReferenceError: data is not defined,
but instead, it will print undefined.
Why has this happened?
Just read the definition again about hoisting, JavaScript hoisted the variable declaration to the top of the scope, and this is what code looks like to the interpreter.
Because of hoisting, we can use variables or functions before they are declared. Just remember hoisted variable is initialized with a value undefined
.
Letâs take a deeper look at the variable
and functional
hoisting to understand how and what this means.
Variable Hoisting
In JavaScript, there are three different ways to declare a variable â var
, let
, and const
. There are two steps: variable declarations and initialization.
JavaScript Interpreter only moves the declaration to the top of the code and not initialization.
Variable Hoisting acts differently depending on how the variable is declared. Letâs first understand var
hoisting.
When JS interpreter hoist a variable declared with var
, it initializes its value to undefined
.
If we forgot the declaration and only initialize the value, the variable isnât hoisted. Trying to read the variable before it is initialized and not hoisted will throw a ReferenceError
exception.
However, initialization also causes declaration (if not already declared). The code below will work, as even though it isnât hoisted, a variable is initialized and effectively declared before it is used.
By now, you all may be thinking, itâs kind of weird that JavaScript allows us to access variables before theyâre declared. This is unusual from JS and can lead us to more confusion and lead to errors.
Thatâs why let
and const
were introduced in ECMAScript 2015.
Variable declared with let
and const
are hoisted but not initialized with a default value, unlike var
. Trying to read the variable before itâs declared will be thrown an exception of ReferenceError
.
Notice that the interpreter still hoists the variable âdataâ: the error message indicates that the variable is initialized somewhere.
As we have seen above, variables are hoisted to the top of their scope. Next, letâs look at how function scoped variables are hoisted.
Function hoisting allows us to call a function before it is defined. Letâs take an example and try to guess the output
Following code runs successfully and outputs: âMy catâs name is Tigerâ. Why?
Because function declarations are hoisted.
This makes sense, as variable assignments arenât hoisted. If we try to call the variable that the function expression was assigned to, weâll get a TypeError
or ReferenceError
, depending on the variableâs scope.
Conclusion:
Letâs summarize this article:-
We should make it a habit to use let
and const
over var
to avoid unnecessary errors.
Thanks for reading, I hoped you learn about scope and hoisting in JavaScript. Please share your views in the comment section, feedback is appreciated.
Check out my other articles on How to load scripts efficiently.
and Difference between map and forEach.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.