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