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) };
I’m working through some problems from my textbook in my class to prepare for our next exam, and can’t figure out how the above evaluates.
Mostly, I don’t understand the call z=g(f), as when f is evaluated, it isn’t provided an argument, so how does it evaluate at all? How does it know what y is?
Also, as far as scoping goes, I believe javascript treats most everything as global variables, so the last x that is set would be the x value used in function f, correct?
Thanks for any help!
Please note, these are extra problems in the back of the book I’m practicing to prepare for the exam, these are not direct homework questions.
This sets the global x to 5, then (before any function calls) 10. The braces don’t create a new scope.
You pass
finto thegfunction (it becomes formal parameterh). That is then called withx == 7(gis a function with its own scope, so thisxshadows the global).Entering
f,xbecomes the formal parametery;yis thus 7.(x + y) - 2is then10 + 7 - 2.