This content originally appeared on DEV Community and was authored by fotiecodes
Hello, everyone!
In this post, we'll look at the Concept of Hoisting in Javascript. We'll go over everything you need to know about hoisting and why it's crucial to know. Don't forget to bookmark this page so you can come back to it later.
General Meaning
Meaning of the Word In English, hoisting implies "to raise(anything) using ropes and pulleys."
To put it another way, we may say that we are bringing something to the top. Now, let's talk in terms of Javascript: Meaning "lifting variable declarations to the top" refers to the process of bringing variable declarations to the top or before the variable usage.
What then is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations to the top. A variable is created when a declaration is made, i.e: var a; Initializing involves giving it a value, i.e: var a = 2, for example.
var a; // Declaration
a = 2; // Initializing
var a = 2; // Declaration & Initializing
A variable in JavaScript can be used before it has been defined.
Simply said, everytime you declare a variable in javascript, whether after or before it is used, the javascript engine in the browser moves that variable to the top, preventing the browser from returning an undefined error.
This signifies that javascript declarations are hoisted, and hoisting is the act of bringing declarations to the top.
a = 2; // Initailized
console.log(a); //used
var a; // Declared
// output -> 2
var a; // Declared
a = 2; // Initailized
console.log(a); //used
// output -> 2
Because every declaration advances to the top of the current scope, both will provide the same result (to the top of the current script or the current function)
Declarations with let & const:
Let and const variables are hoisted to the top of the block but not initialized.
Meaning: The variable is recognized by the block of code, but it cannot be used until it has been declared.
If a let variable is used before it is defined a ReferenceError is thrown. similarly, using a const variable before it is declared, will return a syntax error, hence the code will not run. for example;
let
a = 'fotie';
let a;
// this will result in a reference error
const
a = 'fotie';
const a;
// this code will not run
It's worth noting that: JavaScript only hoists declarations, not initializations.
Thanks for reading.
DID YOU LIKE THIS POST. FOLLOW FOR MORE!
Originally published on codementor on Mar 05, 2022.
This content originally appeared on DEV Community and was authored by fotiecodes
fotiecodes | Sciencx (2022-03-28T07:34:34+00:00) Hoisting in javascript. Retrieved from https://www.scien.cx/2022/03/28/hoisting-in-javascript-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.