JavaScript local and global variable confusion

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

In JavaScript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:

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

This is called hoisting.

Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.

Solution 2 - Javascript

It is not replacing the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them.

Try this:

var myname = "initial";

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

c();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBharat SoniView Question on Stackoverflow
Solution 1 - JavascriptEmptyArsenalView Answer on Stackoverflow
Solution 2 - JavascriptSridhar RView Answer on Stackoverflow