1. Traps to avoid in JavaScript:
the short list
Vlad Didenko December 18th, 2008
2. Global Variables
<script type=quot;text/javascriptquot;>
var count;
// ………Hundreds of lines of code later………
………function ( tag ) {
count = getElementsByTagName( tag );
………
}
</script>
Name collisions, hard to understand code, extra documentation and
maintenance.
Re-factor, make sure to use «var» in inner scopes.
3. The quot;+quot; operation
Adds if both operands are
numbers.
Runs toString() on all
operands and concatenates if
one of the operands is not a
number.
<input id=quot;in1quot; /><input id=quot;in2quot; />
<button onclick=quot;alert( [ 0, '-' ] +
getElementById('in1').value + getElementById('in2').value
);quot;>Add</button>
4. Default parseInt() base
If string starts with «0», parseInt expects an octal number. As
«9» is not an octal digit, parseInt stops at «0».
month = parseInt( '09/03/2008'.split( '/' )[0] );
0
Solution: ALWAYS use explicit base, like in:
parseInt( value, 10 )
5. New-line and quot;;quot; insertions
Browsers made to
quot;correctquot; user errors.
Syntax becomes
unpredictable - semicolon
inserted after the «return»
in the example.
Do not begin objects on a
new line as a habit.
6. Bad scope assumptions
var arr = [quot;firstquot;, quot;lastquot;];
Functions DO create
var v = 20;
scope.
function test(){
var v = true;
Other blocks in curly alert(v);
braces do NOT create };
scope. test(); // true
for (i in arr) {
var v = arr[i];
This is different from };
most other languages. alert( v ); // quot;lastquot;
7. typeof() ambiguity
Avoid: Use instead:
var a = null; typeof( a ); var a = null; a === null;
quot;objectquot; true
var b = [1,2,3]; typeof( b ); Object.prototype.toString.apply( [1,2,3] );
quot;objectquot; quot;[object Array]quot;
[ typeof( NaN ), typeof( Infinity ) ]; [ isNaN( NaN ), Infinity === Infinity ]
quot;numberquot;, quot;numberquot; true, true
8. Fun with falsy
NaN, 0, '', false, null, and
undefined evaluate to false in
conditional statements: undefin
x==y 0 NaN '' false null
ed
if ( null || false )
F
0 T T T F F
{ alert( quot;Truthyquot; ); }
else
✓ { alert( quot;Falsyquot; ); } F
NaN F F F F F
Be careful, though, when '' T T T F F
F
comparing them to each other:
false T F T T F F
if ( null == false )
{ alert( quot;Expected.quot; ); }
else null F F F F T T
✓ { alert( quot;Gotcha!!!quot; ) };
undefin
F F F F T T
Use the «===» operator ! ed
9. O'REILLY MEDIA, INC.
MAY 2008
ISBN-10: 0596517742
ISBN-13: 978-0596517748
JavaScript: The Good Parts
by Douglas Crockford