JavaScript is a powerful language, but there are certain syntactical and behavioral pitfalls in the language that a newcomer may fall for. These pitfalls generally arise due to properties such as type coercion and evaluation methodology of == & === operator.
1. Uncaught TypeError: Cannot read property. If you're a JavaScript developer, you've probably seen this error more than you care to admit. This one occurs in Chrome when you read a property or call a method on an undefined object.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Boolean type conversion.
'' == '0' //false
0 == '' //true
0 == '0' //true
false == 'false' //false
false == '0' //true
false == undefined //false
false == null //false
null == undefined //true
" \t\r\n" == 0 //true
As well as the difference between null
and undefined
. As listed in the table above, comparing null
& undefined
with ==
returns true, but with ===
it returns false. This behavior makes sense once you understand that undefined
is very different from a variable having a null
value, and something holding the value undefined
is different from something being undefined.
Don't accidentally leave a trailing comma in an object definition literal or IE will fail and you won't notice until much later because you never use IE for development and by then it could suck figuring out what happened.
var foo = {
bar: "bar",
baz: "baz",
};
Note @JulianR's comment:
In arrays, IE doesn't fail directly by throwing some syntax error, but will fail when you try to use the array because the added comma makes IE think there's one more element in the array, with value undefined
, than there actually is. So if you ever have an error because for some reason the last element in an array is undefined
: it's a comma.
Admittedly I've been guilty of some of these in the past, for your amusement it's the ones in bold:
eval
eval("obj."+prop);
with
statementsparseInt(str, base)
without specifying the base
argument.this
in timer/callback functions.setTimeout("someFunc(myScopedVarWhoops)");
$(1).plus(1)
anyone? ;-) continue
without incrementing or adjusting the conditional variable.var
in or before for
statements. for (i=0;i<10;i++)
return condition ? true : false;
instead of return condition;
try...catch...finally
statements to catch errors instead of using if
statements to check variables.{ 0: "Foo", 1:"Bar", 2:"Foobar" }
instead of [ "Foo", "Bar", "Foobar" ]
parseInt()
on user input
parseInt("1,000") // -> 1, wrong!
+"1,000" // -> NaN, correct!
Some already mentioned:
===
) operators whenever possible;
terminating statements properlyfor...in
loops on arraysMight think of some more after I've slept :-)
var
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With