BeFruit

Thursday, June 14, 2007

Typed variables in JavaScript

JavaScript is a rather permissive language, and it lets you write code without annoying you with variable declaration or typing. It is good for simple functions like this:
function selectOptionByValue(oSelect, value){
oSelect.selectedIndex = -1;
for (i = 0; i < oSelect.options.length; i++){
if (oSelect.options[i].value == value){
oSelect.selectedIndex = i;
break;
}
}
}

with the following HTML:
<select id="qualitySelect">
<option value="0">Bad</option>
<option value="1">Average</option>
<option value="2">Good</option>
</select>

if you call:
selectOptionByValue(document.getElementById('qualitySelect'), 2);

the "Good" option is selected.

But what really happened? The function compared the value "2" associated with "Good" with the integer 2.
This is convenient as you don't have to think of it, it works.

But in more complex projects, this permissiveness can make debugging extremely difficult. If you assigned a variable that you were considering as an integer with a string value, all your next processing will fail, but JavaScript will not complain. So a bug that could be detected early arises much later, in a completely different place.

There is not a single solution for this, as JavaScript is not a compiled language where the compiler could signal incorrect type assignments.
The first thing is to declare all variables with "var".
If you want to compare two values in a typed way, use === instead of == and !== instead of !=. '2' == 2 is true where '2' === 2 is false.

A good starting point is to use a tool like the free JSLint that warns you about all the risky code that could hide potential bugs.
This will not eliminate all the bugs from your code, but help you concentrate on the logic instead of the syntax.

Labels: ,

0 Comments:

Post a Comment



<$I18N$LinksToThisPost>:

Create a Link

<< Home