Loading Now
×

HOSTING IN JAVASCRIPT

HOSTING IN JAVASCRIPT

Actually, we don’t need to do anything about hoisting. It’s a default behaviour of JavaScript. I have previously discussed the “behind the scenes” of JavaScript. There, you may have seen that JavaScript brings all declarations to the top before anything else. This is essentially hoisting.

Since hoisting is a default behaviour, all functions in JavaScript are hoisted during the creation phase. Therefore, we can call a function even before declaring it.

> aFunc();

function aFunc() {

}

var a = 10;

var b = 20;

var sum = a + b;

console.log(‘Sum: ‘ + sum);

Sum: 30

< undefined

This works because of JavaScript’s default behaviour during the creation phase. I have discussed the creation phase earlier, but for convenience, I will highlight a few points here as well:

  • A list of arguments is created for all the arguments passed to the function.
  • The code scans for all functions and stores each function in a variable object, which typically points to the function.
  • Then, the code searches for variable declarations. For each declared variable, it sets an undefined property.

Afterward, the code moves to the execution phase and executes line by line according to the execution context. Because of this, due to the function declaration being hoisted in the creation phase and the function call being executed in the execution phase, we can use a function even before declaring it. However, function expressions do not work this way. In a function expression, we store the function in a variable. During the creation phase, that variable is set as undefined. The actual function is executed later, so if we call the function before declaring it, it will show an error stating it is not a function, as it is just a variable at that moment.

name();

var name = function() {

  console.log(‘My name is Zonayed Ahmed’);

}

Output:

> name();

Uncaught TypeError: name is not a function

    at <anonymous>:1:1

Similarly, we can use a variable before declaring it. Because of the creation phase, if you use a variable before declaring it, no error will be shown, but it will show undefined as the variable is set as undefined during the creation phase:

console.log(‘Value: ‘ + a);

var a = 10;

Output

> console.log(‘Value: ‘ + a);

Value: undefined

However, if you never declare that variable, it will show an error when you try to use it.

console.log(‘Value: ‘ + x);

Output:

Uncaught ReferenceError: x is not defined

    at <anonymous>:1:25

Post Comment