Hoisting, Block-level Scoping & Arrow Function.

Hoisting — If you are new to javascript then you will find hoisting a little bit wired but in this article, I will simplify the concept of hoisting. Hoisting is a javascript concept, not a feature. So what the heck is hoisting??

In general, hoisting is a mechanism where variable and function declarations are moved to the top of their scope.

And always remember that javascript only hoists declarations, not initializations. Well, that’s a lot of words now see some examples.

If you run the piece of code in C based language (like C++, Java, C#) it would throw you a ReferenceError at the very beginning of the code. But in javascript here comes the magic of hoisting. At the runtime, javascript moves all variable declarations and functions at the top of the scope.

The same code will look like this after the interpreter runs through the code.

Let’s see another example —

In the above example, it will throw a ReferenceError. Cause javascript only hoists declarations, not initializations.

If you use let or const like this you’ll get an error. Javascript does not hoist declarations with let and const.

function hoisting — Let’s now talk about function hoisting. Javascript hoists function declarations, not function expression. Now see an example —

In this example, the function foo is successfully called cause it's a function declaration and that’s why it is hoisted. Inside of the function foo, it will show the output undefined cause as we saw in the previous example, the variable bar is moved to the top of its scope.

The above code will look like this after the interpreter runs through it —

Block Scoping — Let’s simplify block scoping. Literally, if you see the {curly brackets} it’s a block. The let and const allow us to declare variables in the block scope. That means the variables exist only within the scope and not accessible from the outside.

Arrow function — The arrow function allows us to write a short syntax for function. Example —

Things you have to remember before using the arrow function.

They do not have their own this, that's why they are not suitable for defining object methods. Arrow functions are not hoisted, you have to declare them before use. You can only omit the return if the function is a single statement.

spread operator (…) — Spread operator consists of three consecutive dots written like this the spread operator allows you to spread out elements of an iterable object such as an array, a map, or a set. You can use the spread operator in a lot of ways. Some examples below —

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store