Hoisting

Example 1 : Function Declaration Hoisting

1  sayHello();
2
3  function sayHello() {
4    console.log("Hello!");
5  }
In this example, we call the sayHello() function before it is actually defined. However JavaScript hoists function declaration to the top of their scope, so the function can be called before its declarations without causing a error. The output will be "Hello".

Example 2 : Variable Declaration Hoisting

1  console.log(x);
2  var x = 5;
In this example, we try to access the value of the variable "x" before it is declared. However javaScript hoists variable declaration to the top of their scope, so the variable is created before the console log statement is executed. The output will be "undefined" because the variable is declared but not assigned a value at the time "console log" statement.

Example 3 : Hoisting within a Function

1  function foo() {
2    console.log(x);
3    var x = 10;
4    console.log(x);
5  }
6  foo();
In this example, we define a function "foo" that contain variable declaration and assignment. When we call the function JavaScript hoist the variable declarations "var x" to the top of the functon's scope. However, the assignment "x=10" is not hoisted, so the first "console.log" statement will output "undefined", and the second "console.log" statement will output "10"
Lorem