DEV Community

Nashmeyah
Nashmeyah

Posted on

Hoisting

JavaScript variables can be declared after they have been used.

Before jumping into examples and how hoisting effects programming, you must know what hoisting means. Hoisting is JavaScript's default behavior to moving all declarations to the top of the current scope, whether that is the script or the function you are working within. Functions can also be hoisted, but there are two types of functions;

  1. Function declarations
  2. Function expressions

Function declarations can be hoisted to the top, here is an example

hoist(); // Output: "A hoisted function'"

function hoist() {
 console.log('A hoisted function');
};
Enter fullscreen mode Exit fullscreen mode

A function expression cannot be hoisted to the top

expression(); //Output: "TypeError: expression is not a 
function

var expression = function() {
   console.log('Will this work?');
};
Enter fullscreen mode Exit fullscreen mode

Function definition hoisting only occurs for function declarations, not function expressions.

Var initialization can be hoisted and let and const are hoisted to the top of the block, but not initialized The code knows of the variables existence, but it CANNOT be used until it has been declared.

Var:
b = 20; // Assigns 20 to b

elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x;        // Display x in the element

var b; // Declares b
Enter fullscreen mode Exit fullscreen mode

Let:

carName = "Volvo";
let carName;

//ReferenceError
Enter fullscreen mode Exit fullscreen mode

Discussion (0)