Scope & Hoisting in JavaScript

So considering the above section about scopes, cleared the basics let’s move on to hoisting.

Hoisting

In-formerly Hoisting is referred as a mechanism where function/variables declarations in the program are moved to the top of their scope before code execution. Meaning that no matter where functions/variables are declared, they are moved to the top of their scope regardless of weather they were globally scoped or locally.

This is what is perceived externally, but internally the process is little different. According to MDN

The variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

It’s a bit confusing and not easy to be grasped upon in a single read. Let’s see some examples to know what that actually means.

In any programming language, a function definition and a call like this is pretty standard, no errors here we get our output.

Languages that does not support hoisting or if we disable hoisting this above implementation will throw an error catName is not defined, even though it is.

Error

Again to the definition of hoisting

The variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

Here the function declaration is put in memory at compile time, so it really does not matters from where do we call the function as JS knows where exactly is the declaration stored in the memory. Hope that clears, what hoisting actually is.

Let’s know more about Hoisting using examples.

  • JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. It is the same example above

  • Hoisting let’s use initialize and use variables before they are declared.

  • JavaScript only hoists declarations not initialization/assignments to that variable.

As only declarations are hoisted, initializing a declared variable after use will give undefined.

  • Function expressions are not hoisted.

This was a brief about Hoisting used in JavaScript. If you liked what you read, follow and Clap!

Google

read original article here