Day 1 - What is hoisting and how to prevent it in javascript?

Day 1 - What is hoisting and how to prevent it in javascript?

What is hoisting?

The default behavior of the javascript interpreter is to move variable and function declarations to the top. This behavior is called Hoisting.

Take a look at the below code snippet!

var x = 100;
function announce() {
  console.log('Hello World');

// Output :
// undefined
// Hello World

Note that, we are calling the variable 'x' and function 'announce' even before we are declaring it. In most languages, this would result in an error! But it works in javascript due to hoisting! Now coming to the output itself, we see that the value of the variable is not printed but the function is executed properly. This is because, for variables, only the declarations are hoisted not the initialization. So we don't get an error while calling the variable before its declaration statement. But at the same time, we won't get the initialized value either.

As you can see, clearly hoisting makes our code unpredictable because, even if a variable is assigned a value only once, its value is not the same throughout. Hence many developers don't prefer hoisting.

How to prevent hoisting?

Javascript interpreter will hoist lines starting with var and function We can prevent hoisting by using let or const keywords instead like below.

let x = 100;
let announce=function() {
  console.log('Hello World');

Hoisting will not take place for the above code since they don't start with var or function. So if we try to access the variable 'x' or the function 'announce' before declaration, we will get a not defined error.