Tuesday, September 25, 2007

javascript undefined and strict comparators

Use === and !=== when you want to compare types as well. Otherwise you can get things like "" == 0 evaluating to true.

There is a difference between a variable being undefined and null. Use if(someObject) since it should evaluate both undefined and null to false.

from http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx

You can't overload a function.
Developers who are used to languages like Java and C# overload methods all the time. Well, in JavaScript, there are no overloads, and if you try to define one, you won't even get an error. The interpreter will just pick the latest-defined version of the function and call it. The earlier versions will just be ignored.

Undeclared variables are global.
Always, always declare your variables using the var keyword. If you don't, your variable is global. So anyone who makes the same mistake as you (or more likely, if you do the same mistake in two different places) will create nice conflicts which give rise to very difficult-to-track bugs. Even loop counters should be properly declared.

There is actually a good way to do some basic sanity checks on your script files (like multiple declarations, forgotten declarations, unassigned variables, etc.): in Firefox, go to the about:config url and look for the javascript.options.strict entry.

from http://joeyjavascript.com/2007/04/25/javascript-difference-between-null-and-undefined/

n JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value:

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Unassigned variables are initialized by JavaScript with a default value of undefined.

JavaScript never sets a value to null. That must be done programmatically. As such, null can be a useful debugging tool. If a variable is null, it was set in the program, not by JavaScript.

null values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: 0
String: “null”

undefined values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: NaN
String: “undefined”

No comments: