Search code examples
javascriptpass-by-referencevar

why passing var to a function make this var immutable inside?


i am new to js and i wanna understand the difference between x variable in these three cases and why the third case in this code give me x=10 still confused

      var x = 10;
      function test(){
            var x = 15;
      }
      test();
      console.log(x)// return 10

      ///////////////////////////
      var x = 10;
      function test(){
             x = 15;
      }
      test();
      console.log(x)// return 15

      ////////////////////////////
      var x = 10;
      function test(x){
             x = 15;
      }
      test();
      console.log(x)// return 10

Solution

  • var x = 10;
    function test(){
      var x = 15;
    }
    

    new x was created in function scope

    var x = 10;
    function test(){
      x = 15;
    }
    

    x belong to outer scope

    var x = 10;
    function test(x){
      x = 15;
    }
    

    Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

    Mdn