Tackling JavaScript strict
warnings
Credits: This tutorial is written and
contributed by
Alex Vincent with contributions
by Robert Ginda. Alex is a long
time visitor of JavaScript Kit, and participant of CodingForums.
Netscape 6 and the Mozilla browser introduce a new feature for
debugging efforts: strict warnings. These are messages from the JavaScript
engine inside the browser about some very common minor mistakes in
JavaScript. These mistakes, unlike errors, do not stop execution of the
webpage. But they do slow it down a bit, and they're very easily fixed.
Before we get into the types of strict warnings, let me show you how to
find them first. In Mozilla, go to Edit, Preferences, Debug, and check the
box for "Show strict JavaScript warnings". Then, in the JavaScript Console
(Tasks->Tools, JavaScript Console in Netscape 6 and older Mozilla builds;
Tools->Web Development->JavaScript Console in newer Mozilla builds),
select the Warnings panel. (The All panel will do as well; it shows errors
and strict warnings, in the order of when they happened.)
So let's take a moment now to review the types of warnings you would
see in a browser.
Variable Declaration Warnings
Error #1:
This happens when we fail to declare the existence of the variable
using var or const. We've often tended to do
this deliberately, to set a global variable from within a function:
function go() {
blue = "#00007f" // throws warning
return true
}
x = go()
alert(blue) // returns "#00007f"
Solution: There's really no reason not to declare the existence
of blue
outside the function (even after the function definition, since functions
don't execute until we call them).
function go() {
blue = "#00007f"
return true
}
var blue;
x = go()
alert(blue) // returns "#00007f"
Error #2:
We see this one fairly often too. Especially when we say if
(document.layers) or if (document.all), with which we
simply assume the parent object exists:
foo = new Object();
var k = foo.bar; // warning
alert(k);
Solution: It's easy to fail-safely detect a property:
var foo = new Object(), k;
if (typeof foo.bar != "undefined") {
k = foo.bar
} else {
k = undefined
}
alert(k);
Error #3:
This happens when you use a var or const
statement on a variable name you defined earlier in the function or at a
higher scope (say, in the global scope outside all functions). One typical
cause of this warning is the following:
if (this > 0) {
var response = true
} else {
var response = false
}
Solution: JavaScript doesn't need the second var
keyword here. Simply use:
var response;
if (this > 0) {
response = true
} else {
response = false
}
|