Top 10 javascripts errors and mistakes not to do
1. Mistake: Assuming string.replace("", "") will replace all occurrences.
No !! It just replaces the first one !!
var string = "Library of China";
string = string.replace(" ", "-");
string will contain "Library-of China";
Correct writing :
var string = "Library of China"; string.replace(/ /g, "-"); "Library-of-China"
2. Mistake: Assuming using double-quotes to surround RegExp is the same as slashes
Fact: new RegExp("^mycooldomain\.com") is not the same as /^mycooldomain\.com/. In the first one. The dot is interpreted as a wildcard and will accept anything such as exclamation marks!
Remember : Always double your backslashes when writing a regex in a string in Javascripts.
In fact backslash for escaping does not have same effect in both writing. When in double-quotes, you will need to double-escape like this \\. to get the same behavior as when the regular expression is declared within slashes like /dotonly\.com/
In other words this is wrong and will allow exclamation marks in a hostname !:
var regExpHostname = new RegExp("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"); // RFC 1123
Good writing:
var regExpHostname = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; // RFC 1123
3. Mistake: Thinking that regular expressions' dot (.) will match a newline
Javascript is one of the only language where regular expressions modifier "m" is not available to transform the wildcard dot characters to match newline (the other language where this is not possible is VBScript). Instead you can use this notation [\S\s] to match newline (and other spacing). In other languages you would use regular expression modifier "m".
Let say you want to match something like
%begin%
stuff here
%end%
Wrong: var example = test.match(/%begin%(((?!%end%).)*)%end%/m);
Correct writing : var example = test.match(/%begin%(((?!%end%)[\S\s])*)%end%/);
4. Mistake: Using three equals === on null check
if (myCuteVariable === null)
Problem: This will not cover undefined case
Good writing :
if (myCuteVariable == null) // covers both null and undefined
People who use jslint with the check for null won't like this. I usually then use a function such as :
if (typeof valid === "undefined") {
// helper functions to pass lint
var valid = function (param) {
return param !== null && typeof param !== "undefined";
};
var nul = function (param) {
return param === null || typeof param === "undefined";
};
}
Good writing that passes jslint :
if (nul(myCuteVariable)) // covers both cases and passes jslint
Crash on null check.
This is a twist of #3, but I mention it since I saw people doing this
if (output.Sender !== null && output.Sender.length !== null)
This will crash when Sender is undefined
TypeError: Cannot read property 'length' of undefined.
Basically if undefined, the checks for !== null does not catch undefined and goes with second block.
You should learn that != is a shorthand for the double checking of :
typeof variable != "undefined"
*and*
variable !== null,
so it has more wide coverage.
5. Mistake: Assuming ! will cover undefined : if (!timer)
Problem : "!" Does not "work" on undefined values, see example below
var timer; // undefined
if (!timer)
{ // will never go there !
timer = new SuperAwesomeTimer();
}
Good writing :
var timer;
if (timer == null) // will also cover the undefined value
{ // will correctly go here
timer = new SuperAwesomeTimer();
}
Note : Yes this happens. Except for the name of SuperAwesomeTimer, it is real example of a someone else's bug I had to fix.
Note: On Chrome it does not happens.
6. Mistake : An empty string will fail the if (string) test.
var string = "";
if (string)
{ // will not go there.
}
This is a simplification of an actual bug I came across. Whenever the user would enter an empty string -- which was an accepted value -- the backend would never forward the value since it didn't pass the if (string) test.
7. Mistake : substr vs substring
Javascript has both similar functions which makes it hard to recall which one is which.
str.substr(start[, length])
str.substring(indexStart[, indexEnd])
8. Not knowing typeof null === "object"
When testing a variable type, note that if the variable's value is null, it will assert true to typeof myVar == 'object' !
if (typeof data === 'object' && typeof data.error === 'string')) { // potential CRASH HERE!
// use data.error
}
Correct writing
if (data && typeof data === 'object' && typeof data.error === 'string')) {
// use data.error
}
Recent Comments