0

i have this code in java script

var x = 5;
function f(y) { return (x + y) - 2 };
function g(h) { var x = 7; return h(x) };
{ var x = 10; z = g(f) };

z value is 15. why? the expression (x+y)-2 is being evaluated as (10+7)-2. why does x get the value of 10, and not the value of the previous block, where x = 7? thanks for the help

mike
  • 767
  • 2
  • 10
  • 18

2 Answers2

1

You can completely delete the first assignment. It gets overwritten before you call g(f).

Also, you can remove the parentheses of the last block as there is no block scope in JS (actually block scope got introduced with let, so you wanna use that instead).

var x = 5;

function f(y) { 
    // global variable x is 10 -> 10 + 7 - 2 = 15
    return (x + y) - 2; 
}

function g(h) { 
    // x gets declared locally - local value will be used
    var x = 7;   
    return h(x); // f gets called with y = 7
}

x = 10; //global x gets changed
z = g(f);

... and always place your semicolons. Even though they maybe look optional but in some cases they are obligatory.

1

Value of variable x is 10 at global execution context. When function f is finally called the value of the argument which is y, this y actually represent value of x at local execution context of function g, here x is 7.

       var x = 5;
        function f(y) {
         return (x + y) - 2 ;  
          }; // value of global var x is 10, value of parameter passed is 7
            // this value comes from the local var x of g function's  execution context.

        function g(h) { 
        var x = 7; return h(x); };

       { var x = 10; z = g(f); };

       console.log(z);
Rafique Ahmed
  • 117
  • 2
  • 8