Bit confused between JavaScript Hoisting and Functional Scope

If I'm not wrong var lives is functional scope, because it's inside in function sandeep(). But if I'm doing console.log(lives) outside above the function then still I am getting console result as - New Delhi why? Can any one help me. (Is it because of Hoisting? it's moved on top...)

Screen shot without var define inside function 在这里输入图像描述

Screen shot with var inside function 在这里输入图像描述

Screen shot- write console.log after function call now it's giving undefined 在这里输入图像描述

I got my answer - It was my mistake, my chrome browser didn't refreshed properly. Thanks for every one for their answers. 在这里输入图像描述

console.log("Lives become global variable " + lives); 

function sandeep() {
    lives = "New Delhi";
    return lives;
}
sandeep();

You are right about the fact that

var lives is functional scope

But you haven't declare the variable in the function. You need to use var lives = "New Delhi" so that its scope is only in the function in which it is declared.

If you directly assign lives = "New Delhi" , it is assigned to global window object. Open browser console and try this.

a = 1 and then window.a You'll find that window.a is 1 .

Let me know if it helps.


If I'm not wrong var lives is functional scope

This is right but you forgot the var in front of lives. If you define it as a variable you will get an error:

console.log("Lives become global variable " + lives); 

function sandeep() {
    var lives = "New Delhi";
    return lives;
}
sandeep();
链接地址: http://www.djcxy.com/p/96284.html

上一篇: 为什么Firefox比Chrome更早地触发加载事件

下一篇: JavaScript提升和功能范围之间的混淆