Need to clarify scope issue in javascript

I have this code

var Variable = "hello";

function say_hello ()
{
    alert(Variable);
    var Variable = "bye";
}

say_hello();
alert(Variable);

Now, when I first read this code, I thought that it would warn “hello” twice, but the result that I get is that it warns “undefined” the first time and “hello” a second time. can someone explain to me why?

+4
source share
3 answers

In JavaScript, all declarations varin a function are processed as if they appear at the very top of the function body, regardless of where they are actually located in the code. Therefore, your function was interpreted as if it were written like this:

function say_hello() {
  var Variable;
  alert(Variable);
  Variable = "bye";
}

, , ; , var . , "Variable", . alert() .

+7

, , - . , , : function say_hello() { var variable = "bye"; alert(variable); }

+1

. , var " ". defining Variable after you alert it say_hello, undefined. " ", "bye" say_hello, "" .

var Variable = "hello";

function say_hello ()
{
    alert(Variable);
    //Variable = "bye";
}

say_hello();
alert(Variable);
0
source

All Articles