Are variables declared with let or const hoisted?

前端 未结 6 1022
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 04:58

I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...

console.log(typeof name         


        
6条回答
  •  失恋的感觉
    2020-11-21 05:46

    in es6 when we use let or const we have to declare the variable before using them. eg. 1 -

    // this will work
    u = 10;
    var u;
    
    // this will give an error 
    k = 10;
    let k;  // ReferenceError: Cannot access 'k' before initialization.
    

    eg. 2-

    // this code works as variable j is declared before it is used.
    function doSmth() {
    j = 9;
    }
    let j;
    doSmth();
    console.log(j); // 9
    

提交回复
热议问题