简体   繁体   中英

Javascript hoisting code snippet

I am going through code snippets of JS hoisting. One of the snippet looks like

var employeeId = 'abc123';

function foo() {
    employeeId();
    return;

    function employeeId() {
        console.log(typeof employeeId);
    }
}
foo(); 

The output would be: function

I have read about hoisting and as per my understanding all the variables would be treated as if they are declared at the top of the function and initialised at the line of their actual declaration/definition. In this case the employeeId function identifier would be declared at the top of the function as var employeeId whose value would obviously be undefined and thus the very first line of the function should throw the error.

Please let me know why the output is function ?

Both var declarations and function declarations are hoisted to the top of the scope in which they occur (in that order); var s get undefined as their value, the bindings for functions get the function as their value. Only after that's done is any step-by-step code in the function executed.

So your example is effectively the same as this:

var employeeId;                           // Declaration
function foo() {                          // Declaration
    function employeeId() {               // Declaration (shadows outer `employeeId`)
        console.log(typeof employeeId);
    }

    employeeId();
    return;
}
employeeId = 'abc123';
foo(); 

thus the very first line of the function should throw the error.

No , function declarations are hoisted along with the value (unless it is declared inside an inner block).

In your code,

var employeeId = 'abc123';

function foo() {
    console.log(employeeId); //will print function body
    return;
      function employeeId() {
        console.log(typeof employeeId);
      }
}

but if the function declaration is inside an inner block

var employeeId = 'abc123';

function foo() {
    console.log(employeeId); //will print undefined
    {
      function employeeId() {
        console.log(typeof employeeId);
      }
    }
    return;
}

This happens function declarations are hoisted before variables.

In JavaScript function and variable declarations are hoisted at the top of the execution context. You need to remember these three rules for on the same.

  1. Variable and function declaration are hoisted at the top of the execution context.
  2. Only declaration gets hoisted, assignments does not get hoisted. Assignment happens where variable was declared.
  3. function declaration has a precedence over variable declaration in the hoisting. 在此处输入图像描述

https://www.codingame.com/playgrounds/7974/understanding-hoisting-in-javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM