Order of hoisting in Javascript detailed

141 Views Asked by At

Question #1.

I understand that "var" is function scoped, but does javascript order the hoist alphabetically? or first come first serve.

function x () {
    var b;
    var c;
    var a;
}

After hoisting, does the result become this or the same result as above:

function x() {
    var a;
    var b;
    var c;
}

Question #2.

I understand that function is hoisted before variables.

When I run this:

function x() {
  var b = 2;
  var c = 3;
  var a = 1;

  function y() {
    var d = 4;
  }
}

console.log(x);

I don't see the "function y()" being printed before the vars.

1

There are 1 best solutions below

0
On

The order in which the variable names are "created" when hoisted doesn't matter, because just creating a variable name (possibly in addition to creating a function tied to the variable name, in the case of a function declaration) doesn't affect anything else. Nothing involved in it has any side effects, so the order in which the interpreter actually creates the variable names is opaque and irrelevant. That's a good thing - it means you don't have to worry about it.

That's assuming you're wondering about how things work at runtime, and don't have any syntax errors. If you do have syntax errors and are declaring variables with const or let, duplicate variable declarations for the same variable name in the same scope are forbidden, so the first duplicate identifier (in the same order as in the source code) will throw a syntax error.

let foo;

function foo() { // <-- This line throws
}

I don't see the "function y()" being printed before the vars.

When you do

console.log(x);

where x is a function, you'll just be given the function source code, which will be exactly as you typed it in the script - the code isn't altered in any way, so any "hoisting" effects won't be visible.