I think there's a mistake in the first example, it talks about for-in being bad but the example doesn't actually use for-in.
> There is no really good reason to predefine the array length.
There are good reasons, though they're usually quite 'sneaky', for example:
function repeatString(str, howMany) {
return new Array(howMany+1).join(str);
}
> 13. Usage of undefined as a variable... that variables isn’t read-only, and any other code can change its value... why take the risk?
There's no good reason to be that paranoid, libraries could also overwrite 'document', 'XMLHttpRequest', 'setTimeout' and a number of other variables that would likely break my code; if any of my libs are so rogue that they overwrite 'undefined' then I've got big problems.
Besides the first example having a mistake, their suggested solution still isn't best practices;
for (var i = 0, len = myArray.length; i < len; i++)
{
...
}
Will perform far faster than doing the comparison on each iteration. Might not be noticeable on an array of 10, but certainly would be on an array of 1k.
Number 4, misuse of closures refactored the code into something equivalent, but both have circular reference memory leak, bad form of the author to create an example of something with other bad code in the snippet.
A much nicer answer would be to refactor into the non-leaking version, which was very straightforward from the first snippet.
function createAlert(a, b, c, d) {
return function() {
alert (a + b + c + d);
}
}
function(a, b, c) {
var d = 10;
var element = document.getElementById(‘myID’);
element.onclick = createAlert(a, b, c, d);
}
This will no longer leak and is much easier to read.
The author tries to give an example of a non-leaking version further down, but unfortunately tryies to delete a variable, which is not allowed in strict mode.
delete element; // bad
a much nicer version is to delete the callback from the element instead (from within the callback closure itself).
delete element.onclick;
(or just use the non-leaking version in my comment in the first place).
This article has numerous errors in the examples and the text. I recommend that anyone not familiar with js to ignore this article and move on to better documentation.
I like things like this, but if the doing new Array(x) is in the list of top 13 mistakes then we are doing pretty good! Also, I've never seen people assign undefined instead of a null.
> There is no really good reason to predefine the array length.
There are good reasons, though they're usually quite 'sneaky', for example:
> 13. Usage of undefined as a variable... that variables isn’t read-only, and any other code can change its value... why take the risk?There's no good reason to be that paranoid, libraries could also overwrite 'document', 'XMLHttpRequest', 'setTimeout' and a number of other variables that would likely break my code; if any of my libs are so rogue that they overwrite 'undefined' then I've got big problems.