Originally published at: http://www.sitepoint.com/three-javascript-quirks-java-c-developers-should-know/
JavaScript can be a deceiving language and it can be a real pain because it isn’t 100% consistent. As it’s well known it does have bad parts, confusing or redundant features that should be avoided: the infamous with statement, implicit global variables and comparison erratic behavior are probably the best known.
JavaScript is one of the most successful flames generator in history! Besides the flaws it has (which are, in part, addressed in the new ECMAScript specifications), most programmers hate JavaScript for 2 reasons:
- The DOM, which they erroneously think is equivalent to the JavaScript language, which has quite a terrible API.
- They come to JavaScript from languages like C and Java. They are fooled by JavaScript’s syntax into believing that it works the same way as those imperative languages do. This misconception will lead to confusion, frustration, and bugs.
That’s why, generally, JavaScript has a worse reputation than it deserves.
During my career, I noticed a few patterns: language features most developers with a Java or C/C++ background assume to be identical in JavaScript, while they are completely different.
This article gathers the most troublesome ones, comparing the Java-way to the JavaScript-way to shown differences and highlight best practices in JavaScript.
Scoping
Most developers start working on JavaScript because they are forced, and almost every of them start writing code before taking a moment to learn the language. Every such developer has been tricked by JavaScript scope at least once.
Because JavaScript’s syntax closely resembles (on purpose) C-family languages, with curly braces delimiting function
‘s, if
‘s and for
‘s bodies, one would reasonably expect lexical block-level scope. Unfortunately, this is not the case.
First, in JavaScript variable scope is determined by functions, not by brackets. In other words, if
and for
bodies don’t create a new scope, and a variable declared inside their bodies is actually hoisted, i.e. created at the beginning of the innermost function in which it is declared, or of the global scope otherwise.
Second, the presence of the with
statement forces JavaScript scoping to be dynamic, impossible to determine until runtime. You might not be surprised to hear that the use of the with
statement is deprecated: JavaScript stripped of with
would actually be a lexically scoped language, i.e. the scope could be completely determined by looking at the code.
Continue reading this article on SitePoint