Fun Learning: Function Oddities
by Pratik Bhonsle
HTML
What output do you expect?
<pre>
var i = 0;
function g(j) {
i++;
output('<<outer :: ' + i + ' :: ' + j);
}
function f(cond) {
g('in-f');
if (cond) {
g('in-f-if');
function g(j) {
i++;
output('>>INNER :: ' + i + ' :: ' + j);
}
g('out-f-if');
}
g('out-f');
}
g('in');
f(false);
g('mid');
f(true);
g('out');
</pre>
<br/>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Scope_Cheatsheet#function_oddities">The source of this oddity...</a>
<br>
<br>
<button type="button" onclick="baffleMe()">Baffle Me!</button>
<div id="Output"></div>
JavaScript
function baffleMe() {
var i = 0;
function g(j) {
i++;
output('<<outer :: ' + i + ' :: ' + j);
}
function f(cond) {
g('in-f');
if (cond) {
g('in-f-if');
function g(j) {
i++;
output('>>INNER :: ' + i + ' :: ' + j);
}
g('out-f-if');
}
g('out-f');
}
g('in');
f(false);
g('mid');
f(true);
g('out');
// Just for output
function output(value) {
$('#Output').append(value + '<br/>');
}
}