Hoisting

Hoisting was thought up as a general way of thinking about how execution context (specifically the creation and execution phases) work in JavaScript. But, hoisting can lead to misunderstandings. For example, hoisting teaches that variable and function declarations are physically moved to the top of your coding, but this is not what happens at all. What does happen is that

variable and function declarations are put into memory during the compile phase

but stays exactly where you typed it in your coding.

Function Hoisting

One of the advantages of JavaScript putting function declarations into the memory before it executes any code segment is that it allows you to use a function before you declare it in your code. E.g.:

catName("Chloe");

function catName(name) {
  console.log("My cat's name is " + name);
}

Even though we call the function in our code before the function is written, it still works. This is because of how context execution works in JavaScript.

Variable Hoisting

Hoisting works well with other data types and variables as well. The variables can be initialized and used before declared. But they cannot be used without initialization.

var x = 1; // Initialize x
console.log(x + " " + y); // '1 undefined'
var y = 2; // Declare/Initialize y


// The following code will behave the same as the previous code: 
var x = 1; // Initialize x
var y; // Declare y
console.log(x + " " + y); // '1 undefined'
y = 2; // Initialize y

results matching ""

    No results matching ""