标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:

I am new to JavaScript and I was doing some practices on local and global variable scopes, following is my code(fiddle):

var myname = "initial"
function c(){
    alert(myname);
    var myname = "changed";
    alert(myname);
}
c();

when the first alert is called, it is showing myname as undefined. so my confusion is why I am not able to access a global instance of myname and if I don't define myname within the function then it will work fine.


if you do alert(window.myname); then you will get values

2018年07月18日06分48秒

dholakiyaankit I've tried using window.myname still it is saying undefined...

2018年07月17日06分48秒

BharatSoni window.myname works in my browser.

2018年07月18日06分48秒

It should work bharat

2018年07月18日06分48秒

dholakiyaankit I've tried in fiddle.. didn't work

2018年07月17日06分48秒

that I've understood, so there is now way to access a global variable with same name as local variable.. ??

2018年07月18日06分48秒

You should be able to access it by doing window.myname. See here: stackoverflow.com/questions/15826751/… But global variables are not usually considered a good practice, and in most cases it'd be better to define a global object and access it through that. i.e. var me = { myname: "initial" } then call me.myname in the function.

2018年07月17日06分48秒

It is not correct to say that variables declaration are moved on top. For example if on line 10 it is written var myname = "initial", the result we see is not like var myname = "initial" on line 1, but actually we see the behavior as if var myname is on line 1 and on line 10 it is assigned value i.e. myname = "initial"

2018年07月17日06分48秒

sir, I am not just trying to change the value.. what you are doing is changing the value of global variable itself.. I want to understand the concept "WHY" it is happening...

2018年07月17日06分48秒

This fixes the problem of alerting undefined, but it eliminates any local variables as it's only using the global variable myname.

2018年07月18日06分48秒

It is not replace the global variable. What is happening is called "variable hoisting". That is, myname var myname; gets inserted at the top of the function. Always initialize your variables before you use them you can refer this stackoverflow.com/questions/11938961/…

2018年07月17日06分48秒