9
Vlad Didenko December 18 th , 2008 Traps to avoid in JavaScript: the short list

Things to avoid in JavaScript

Embed Size (px)

DESCRIPTION

JS.Chi() 12/18/08

Citation preview

Page 1: Things to avoid in JavaScript

Vlad Didenko December 18th, 2008

Traps to avoid in JavaScript:

the short list

Page 2: Things to avoid in JavaScript

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>

Page 3: Things to avoid in JavaScript

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>

Page 4: Things to avoid in JavaScript

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 )

Page 5: Things to avoid in JavaScript

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.

Page 6: Things to avoid in JavaScript

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"

Page 7: Things to avoid in JavaScript

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:

Page 8: Things to avoid in JavaScript

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

Page 9: Things to avoid in JavaScript

JavaScript: The Good Partsby Douglas Crockford

O'REILLY MEDIA, INC.MAY 2008ISBN-10: 0596517742ISBN-13: 978-0596517748