I saw Chander Dhall speak on JavaScript at Iron Yard, which seemed to be a business in one of those buildings by Penn Field in South Austin, on Thursday night. The talk covered a wide variety of things. The first of the two things he said which I found the very most interesting was that one should not be too quick to use var and not put a variable in global scope as there is no way to delete a variable when it is declared with var. In this example...
var x = 0;
y = 0;
delete x;
delete y;
console.log(x);
console.log(y);
...the console will first get a zero in it because x could not be deleted and then will have to deal with the undefined, perhaps writing out "Uncaught ReferenceError: y is not defined" in the case (my case) of Google Chrome. The other interesting thing said almost trended in the opposite direction suggesting that it might be wise to wrap your "global" scope variables in a self-executing function like this...
(function(){
var x = 0;
console.log(x);
})();
...as just about anything may be overpowered by another thing downstream in JavaScript. If you have several AngularJS applications which all declare an "app" variable then the app variable for one app can just overwhelm that of another app variable defined upstream in flow. The scoping here isolates one from that havoc. Even "reserved keywords" like undefined may be overpowered by just setting them to something else by putting them at the left of an equals sign. I'm serious. You can set undefined to a function you author and I almost don't want to think about the hacking creativity that may stem from this sort of thing. A lot of the talk was on stuff I wish I didn't have to think about. Chander showed us a lot of scary stuff that had an "Oh, yikes!" quality. We went out into the badlands. Did you know that every variable has a writable, enumerable, and configurable true/false setting? You largely don't have to think about these because they are, by default, true, yet they are there! Oh, yikes! An Eric McVicker gave a talk on the coming ECMAScript 5 right after Chander's talk and while I didn't stick around for his talk I did make a note of his very first example which showed off the let keyword like so:
var i = 1
for (var i = 0; i < 10; i++) {
console.log('loop ' + 1)
}
console.log(i)
let j = i
for (let j = 0; j < 10; j++) {
console.log('loop ' + j)
}
console.log(j)
I didn't stay to find out what this does. The lack of semicolons above is not a typo.
No comments:
Post a Comment