Javascript
Javascript is a... fun... language. In particular, it has some... fun... and perhaps unexpected behavior when it comes to functional programming, variable binding, and the like. The below examples are a collection of questions asked about a specific piece of Javascript code, and wondering what the answer is. None of these are particularly useful or common examples but yet, the language, by design, must have a consistent answer for what occurs in each of these cases.
In each of the below cases, the answer may be one of (1) a string located in the program, (2) no "it errors", or (3) no, "it returns undefined".
1. Functions bind to...
let x = 'values';
let f = () => x;
x = 'variables';
return f();
Answer
'variables'
2. Can functions explicitly capture values?
let x = 'yes';
let f = (v => () => v)(x);
x = 'no';
return f();
Answer
'yes'
3. Do bound variables persist beyond their local scope?
let f;
{
let x = 'yes';
f = () => x;
}
return f();
Answer
'yes'
4. Can functions can bind variables in a wider scope?
let x = 'yes';
{
let f = () => x;
return f();
}
Answer
'yes'
5. Can functions can bind to future variables?
let f = () => x;
let x = 'yes';
return f();
Answer
'yes'
6. Can functions can bind to future variables defined and declared in a narrower scope?
let f = () => x;
{
let x = 'yes';
return f();
}
Answer
Uncaught ReferenceError: x is not defined
7. Can functions can bind to future variables declared but not defined in a wider scope?
let f;
{
f = () => x;
}
let x = 'yes';
return f();
Answer
'yes'
8. Functions bind more strongly to variables in the same scope as the function...
let f;
let x = 'was declared in';
{
let x = 'was defined in';
f = () => x;
}
return f();
Answer
'was defined in'
9. Functions bind more strongly to...
x = 'global variables';
{
let x = 'wider scoped variables';
{
let f = () => x;
let x = 'same level scoped variables';
{
let x = 'narrower scoped variables';
return f();
}
}
}
Answer
'same level scoped variables'