Variable scope, strange result : javascript

05/02/2018


Hi all, I am getting a strange result when testing variable scope.

var text = "some text!";

console.log("main text == " + text);

f1();

function f1(){
  console.log("f1 text == " + text);
  var text = "f1 text"; // SEE HERE
  console.log("f1 var text == " + text);
}

console.log("main text == " + text);`

produces

main text == some text!
f1 text == undefined // SEE HERE
f1 var text == f1 text 
main text == some text!

while this version

var text = "some text!";

console.log("main text == " + text);

f1();

function f1(){
  console.log("f1 text == " + text);
  text = "f1 text"; // SEE HERE
  console.log("f1 var text == " + text);
}

console.log("main text == " + text);

produces

main text == some text!
f1 text == some text! // SEE HERE
f1 var text == f1 text
main text == f1 text

Why was the second line undefined in the top example?

Edit: Why is it that I can set main scope text variable from within the function but I cannot read it unless I also set it after reading it?

قالب وردپرس