Javascript Hoisting

JavaScript hoisting is a concept in which variables and functions are moved to the top of their scope before code execution. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

For example, consider the following code:

console.log(myName);
var myName = "John";

When this code executed, it will log "undefined" to the console. This is because the variable declaration is hoisted to the top of the scope, but the assignment of the value "John" is left in place. So, the code is essentially interpreted as:

var myName;
console.log(myName);
myName = "John";

The same concept applies to functions. Consider the following code:

sayHello();
function sayHello() {
  console.log("Hello!");
}

When this code is executed, it will log "Hello!" to the console. This is because the function declaration is hoisted to the top of the scope, so the code is essentially interpreted as:

function sayHello() {
  console.log("Hello!");
}
sayHello();

Hoisting is an important concept to understand in JavaScript, as it can affect the way your code behaves. It's important to keep in mind that only declarations are hoisted, not assignments.