W3Fools is an interesting site I came across that highlights the wrong parts of W3Schools. While W3Schools is the most popular online resource for web standards, its content has a lot of serious flaws.
One such problem at W3Schools is variable scoping in JavaScript(w3schools page):
JavaScript has a global scope(global window object to be more precise), that is the place where all global variables go, usage of this must be minimized because in most pages there will probably be scripts from multiple sources, if everyone relies on the global scope, than sooner or later one script will get into conflict with another. The var keyword is not an optional decoration in JavaScript, if we leave out the var, then the global scope is assumed automatically. Here are some examples:
These functions declared global variables, therefore our local variable loses its original value:
something = 'first thing'; function foo() { something = 'foo'; } function bar() { something = 'bar'; } foo(); bar(); console.log(something); //'bar'
These functions declared local variables, no collisions have occurred here:
var something = 'first thing'; function foo() { var something = 'foo'; } function bar() { var something = 'bar'; } foo(); bar(); console.log(something); //'first thing'
W3Schools states the following too:
If you redeclare a JavaScript variable, it will not lose its original value.
While it may not cause an error now it is certainly not a good practice and could lead to confusion and maybe runtime errors in future versions of ECMA Script(JavaScript).
There are also other important facts about the var keyword that are not mentioned in W3Schools:
var is function scoped and not block scoped:
function test() { if (true) { var test = 3; } }
works just like:
function test() { var test; if (true) { test = 3; } }
Either way you will be able to access the variable test after the block. A better example might be:
for (var i=0;i<10;i++) { } console.log(i); //10
The best practice to avoid confusion is to begin each function with a single var declaration and declare all variables in that single var declaration. JSLint can help you with that. And learning more about JavaScript is as easy as watching a couple of videos I outlined in one of my previous posts.
Update:
the best comment this article/issue received so far: http://www.reddit.com/r/web_design/comments/fa9hp/what_they_dont_teach_you_in_w3school_javascript/c1ejet7
Update 2: made the w3schools link weaker.
Update 3: added rel=”nofollow” to w3schools links.
Tags: JavaScript, web
Pingback: István Miklós Antal
Pingback: m.y.ikegami_bot
Pingback: Peter Grond
Pingback: What they don’t teach you in (W3)school: JavaScript variable scoping « Interesting Tech
Pingback: Thought Provoking
Pingback: Charles Allhands
Pingback: 奥山実
Pingback: Javascript Simple Digital Time « Kvijayanand's Blog
Pingback: Scott Radcliff
Pingback: MunichJS