./studio_4.sh
Slides
Studio Materials
The hello scope question
const hello = "world";
function n(hello) {
const g = hello => display;
g(hello)(hello);
return g(hello);
}
n("hello")(hello)There are two things here to break down:
The convoluted way this function is written
The use of the hello named variable to confuse us
To fully understand how this works, we want to break down the inside of the functions, and understand what hello is referring to. Sometimes, it helps to rename hello to something else.
const g = hello => displayThis is just a function that takes in a parameter, hello, and returns display. In this line, we created a new scope for hello and never ever use it, so we can reduce confusion by just replacing it.
We can also just replace g(hello) with the function display, since we know that what it'll return regardless of the parameter
const hello = "world";
function n(hello) {
const g = x => display; // Replace this to remove potential confusion
// g(hello)(hello);
display(hello);
// return g(hello);
return display
}
n("hello")(hello)Then, we can substitute n("hello") with the return of the function, in this case, display.
const hello = "world";
function n(hello) {
const g = x => display; // Replace this to remove potential confusion
// g(hello)(hello);
display(hello);
// return g(hello);
return display
}
n("hello")(hello) // This will apply display(hello)The variable hello in the first display(hello) will use the scope in the function, in this case, it is "hello".
The variable hello in the second iteration will be in the variable in the global scope, in this case "world". So this program will print "hello" then "world".
Feel free to click the link below and run through the stepper.
Last updated