Hoisting

Fatima Alam - Dec 1 '23 - - Dev Community

Image description

https://www.freecodecamp.org/news/what-is-hoisting-in-javascript/

Variable hoisting with var

console.log(foo); // undefined

var foo = 'bar';

console.log(foo); // "bar"
Enter fullscreen mode Exit fullscreen mode

Using an undeclared variable before its assignment will also throw a ReferenceError because no declaration was hoisted:

console.log(foo); // Uncaught ReferenceError: foo is not defined
foo = 'foo';      // Assigning a variable that's not declared is valid
Enter fullscreen mode Exit fullscreen mode

Variable hoisting with let and const

console.log(foo); // Uncaught ReferenceError: Cannot access 'foo' before initialization

let foo = 'bar';  // Same behavior for variables declared with const
Enter fullscreen mode Exit fullscreen mode

The temporal dead zone
The reason that we get a reference error when we try to access a let or const variable before its declaration is because of the temporal dead zone (TDZ).

The TDZ starts at the beginning of the variable's enclosing scope and ends when it is declared. Accessing the variable in this TDZ throws a ReferenceError.

Here's an example with an explicit block that shows the start and end of foo's TDZ:

function foobar(foo = bar, bar = 'bar') {
  console.log(foo);
}
foobar(); // Uncaught ReferenceError: Cannot access 'bar' before initialization
Enter fullscreen mode Exit fullscreen mode

However, this isn't the case when using a var variable before declaration because it is initialized with undefined when it is hoisted:

console.log(typeof foo); // "undefined"
var foo = 'foo';
Enter fullscreen mode Exit fullscreen mode

Function hoisting in JavaScript
Function declarations are hoisted, too. Function hoisting allows us to call a function before it is defined. For example, the following code runs successfully and outputs "foo":

foo(); // "foo"

function foo() {
    console.log('foo');
}

Enter fullscreen mode Exit fullscreen mode

Example ->

Image description

In this only calling the function by addArrow() doesn't call the function with params and so prints undefined
but if called like addArrow(2,3) -> gives typeError coz var was expecting a variable declaration whereas we are expecting function.

Problem of Hoisting with var ->

Image description

what happened was because of the falsy(undefined) value of var while hoisting a condition is being met which shdn't be which brings us to a bug to be taken care of when we code.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player