Web December 11th, 2006
Strictly, this post does not belong to this category. But on the other hand, the following pitfalls are usually the evil source.
Note: the code is intentionally to put in one line, just for your convenience to test it in the FireBug.
1. Unexpected global variables
Declare a variable via var state at any time, whether this variable is in the global scope or local scope. Any variable without declaration resides in the global scope, polluting the global namespace.
2. Caution: Boolean operation ahead
Although the constructed Boolean object is false, the if expression returns true. Why? Because the Boolean is an object, if it is not null, the expression returns true.
If the two values have the same type, test them for identity. If the values are identical, they are equal; if they are not identical, they are not equal.
If the two values do not have the same type, they may still be equal. Use the following rules and type conversions to check for equality:
If one value is null and the other is undefined, they are equal.
If one value is a number and the other is a string, convert the string to a number and try the comparison again, using the converted value.
If either value is TRue, convert it to 1 and try the comparison again. If either value is false, convert it to 0 and try the comparison again.
Any other combinations of values are not equal.
typeof operator is also a safe approach, like if (typeof(arg5) == “undefined”)
3. valueOf vs. toString
The only exception is Date, the toString is used in + operator, while valueOf is used in the comparison.
4. Immutable String
5. Pervasive scope
For C/C++ developer, the declared variable take effects after its declaration, like this:
the output is
The alerts are undefined and 10. The global value x is shadowed by the local variable x. Local variable x is declared in this closure, but not assigned before the first alert, so its value is undefined.
TO BE CONTINUED…