Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 28, 2022 07:34 am GMT

Hoisting in javascript

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; // Declarationa = 2; // Initializingvar 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; // Initailizedconsole.log(a); //usedvar a; // Declared// output -> 2
var a; // Declareda = 2; // Initailizedconsole.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.


Original Link: https://dev.to/fotiecodes/hoisting-in-javascript-1pk4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To