Shadows of JavaScript
2017-02-02 13:23Months ago, Robbie had found this scoping problem in Python, which I reduced to essentials.
I've started finally learning JavaScript, and it has nicer lambdas than Python, and proper hiding of nested functions unlike Perl. But it has the same scope problem:
(I'm not including the HTML framework because DW/LJ would yell at me if I did.)
Output is 'undefined', rather than 12. As in Python, the local variable further down shadows the outer scope variable (doesn't matter if the "g1=12" has a 'var' before it) even for lines before the local variable.
As mentioned before, Perl has proper lexical scoping here (though not for nested functions.) I don't think I can even create similar code in Scheme/Lisp, where the scoping is explicit with parentheses. (There's 'define' but I think that makes a new global, and it didn't work.) In Ocaml I have
Which I suspect is as explicit as Lisp parentheses, in its own way; the print line is obviously outside the following "let ... in...".
I've started finally learning JavaScript, and it has nicer lambdas than Python, and proper hiding of nested functions unlike Perl. But it has the same scope problem:
g1 = 12; function func() { document.getElementById("demo").innerHTML = g1; var g1 = 5; } func();
(I'm not including the HTML framework because DW/LJ would yell at me if I did.)
Output is 'undefined', rather than 12. As in Python, the local variable further down shadows the outer scope variable (doesn't matter if the "g1=12" has a 'var' before it) even for lines before the local variable.
As mentioned before, Perl has proper lexical scoping here (though not for nested functions.) I don't think I can even create similar code in Scheme/Lisp, where the scoping is explicit with parentheses. (There's 'define' but I think that makes a new global, and it didn't work.) In Ocaml I have
let g1="10";; let func () = print_endline g1; let g1="cat" in g1 ;; func();;
Which I suspect is as explicit as Lisp parentheses, in its own way; the print line is obviously outside the following "let ... in...".