?

Log in

Previous Entry | Next Entry

Hoisting Shadows

A bit after writing the previous post on shadowing variables in JavaScript, I came across this page on hoisting. JavaScript re-writes your code so that declarations but not initializations to the top of current scope, meaning the script or function[1]. So

console.log(a);
var a=5;


turns into

var a;
console.log(a);
a=5;


Put that way, it's clear why the problem happens, if not why the language was designed this way.

Does the same thing happen in Python? Searching did not get clear results. I saw pages contrasting JavaScript with Python, which doesn't even *have* declarations. OTOH, the same behavior occurs. So... I dunno.

[1] JavaScipt does not have block scoping the way C and Perl[2] do; scopes are delimited by curly braces, but random curly braces do nothing to isolate variables.

{ a=5; }
console.log(a);


will work just fine. :(

[2] As I was verifying this in Perl, I ran into behavior I'd forgotten. I'd thrown in "use strict;" but wasn't getting the errors I expected. Eventually I recalled that $a and $b have special meaning in Perl (I think for comparison functions), and I guess are pre-declared, and I was using $a a la the above code, so strict didn't complain about trying to access $a before assigning to it. Sigh.

See the comment count unavailable DW comments at http://mindstalk.dreamwidth.org/465980.html#comments

Profile

Phoenix
mindstalk
Damien Sullivan
Website

Latest Month

July 2017
S M T W T F S
      1
2345678
9101112131415
16171819202122
23242526272829
3031     

Tags

Powered by LiveJournal.com
Designed by Lilia Ahner