1

I can't understand why the x after test won't become 30 but still remains 10

  <script>
        function test(){
            var x = 30;
            y = 40;
        }
    </script>


    <script>
        var x = 10;
        var y = 20;

        document.write("before test, x: " + x + ", y: " + y + "<br/><br/>");

        test();

        document.write("after test, x: " + x + ", y: " + y + "<br/><br/>");

    </script>
MY Chen
  • 29
  • 1
  • You create a local x inside the test() function, but edit the global y. – Shilly Mar 14 '19 at 14:39
  • 1
    @Quentin This isn't really about what "var" means. It is about variable shadowing. Those are two very different things to a beginner. – samanime Mar 14 '19 at 14:40
  • @MY_Chen Since I can't leave an answer, I'll just mention it here. This is known as variable shadowing and also has to do with scope. This question talks about it: https://stackoverflow.com/questions/11901427/an-example-of-variable-shadowing-in-javascript – samanime Mar 14 '19 at 14:42

2 Answers2

1

This is because by declaring var x = 30;, you create a variable named x that exists only in the function's scope.

The variable y, however, is only defined at top-level. So when you run the function test, you edit the local x variable, and the global (top-level) y variable.

Seblor
  • 6,947
  • 1
  • 25
  • 46
0

When you define variables they are hoisted at top of its scope. Let me show you how your current code:

function test(){
  var x = 30;
  y = 40;
}
var x = 10;
var y = 20;
test();

Will run like this:

// global scope
var x; // x is undefined
var y; // y is undefined
function test() {
  // function scope
  var x; // x is undefined inside this scope
  x = 30; // x is assigned with value 30
  y = 40; // y is assigned with value 40
  // the global scope y value is assigned
}
x = 10; // x is assigned with value 10
// the global scope x value is assigned
y = 20; // y is assigned with value 20
// the global scope y value is assigned
test();
// when calling test,
// you see x is assigned with its function scope
// and y is assigned with its global scope
// so, at this point
// x becomes 10
// y becomes 40

You can read more about var here in the docs. Also, look in the scope, global scope and local scope.


Also, note that let and const works differently. They are scoped in the block. You can read them in the corresponding links which are linked here in.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • This post was marked as duplicate. But I had to provide my explanation on this. So, re-opened the post and marked as duplicate again. Sorry for this! – Bhojendra Rauniyar Mar 14 '19 at 15:09