Skip to content
Lev Brie edited this page Jan 21, 2015 · 4 revisions

Good parts and bad parts

Douglas Crockford on JavaScript's good and bad parts:

"Every language has good parts and every language has bad parts - it's just inevitable. Every designer intends to create a language composed only of good parts but things always go wrong unexpectedly. Now Javascript is unique in that its good parts are some of the best good parts ever put into a programming language, and its bad parts are some of the worst parts ever put into a programming language."

Always use ===. Never use ==, which does type coercion before doing its comparison. Most significantly, equality with the double equals in JavaScript is not transivitive!

0 == ''          // true
0 == '0'         // true
'' == '0'        // false
false == 'false' // false
false == '0'     // true
" \t\r\n " == 0  // true

Triple equals does "the right thing" in all situations with the notable exception of NaN, which we'll get to.

JavaScript does not have block scope

Great, what does that mean?

Block scope means that variables are valid inside of the block in which they occur or inside of any nested block, and not outside of it. This is not the case in JavaScript.

In JavaScript, variables are declared at the top of the function in which they are declared, no matter where you declare them.

Closures

Like objects, closures are a mechanism for containing state. In JavaScript, a closure is created whenever a function accesses a variable defined outside the immediate function scope. It’s easy to create closures: Simply define a function inside another function, and expose the inner function, either by returning it, or passing it into another function. The variables used by the inner function will be available to it, even after the outer function has finished running. You can use closures to create data privacy in JavaScript using a factory function:

var counter = function counter() {
 var count = 0;
 return {
   getCount: function getCount() {
     return count;
   },
   increment: function increment() {
     count += 1;
   }
 };
};