Based on the frequently asked questions on Stackoverflow:
1 . What does the following code do? Why? (Assume you have firebug or some other debugging tool that declares console
)
var i;
for(i=0; i<10; i++) {
setTimeout(function(){console.log(i);}, 1000);
}
2 . What is wrong (or can go wrong) with this code?
var arr = [1,2,3,4],
sqrArr = [],
i;
//calculate squares of the numbers in array
for(i in arr) {
sqrArr.push(arr[i] * arr[i]);
}
3 . Which code runs faster and why?
var i;
for(i=0; i<100; i++) {
jQuery("#myDiv").append("<span>" + i + "</span>");
}
var i, markup = "";
for (i=0; i<100; i++) {
markup += "<span>" + i + "</span>";
}
jQuery("#myDiv").append(markup);
var i, markup = "";
for (i=0; i<100; i++) {
markup += "<span>" + i + "</span>";
}
jQuery("#myDiv").append("<div>" + markup + "</div>"); //assuming the extra div is okay.
[Edit]: Posting the answers.
1: It will log 11 ten times. The closure passed to setTimeout
holds a live reference to the variable i of the outer scope. It will log the value of i when it is actually run, not when the closure is created. In this case, hopefully the loop completes itself before any of the console.log
is called (1000msec ought to be enough!).
2: for..in
is really meant to enumerate (non built-in) properties of an object. Used on an array, it seems to work because Arrays support enumeration on their indices too. However, if you add any property to Array.prototype (such as popular libraries like Prototype and Dojo do), they will be included in the enumeration as well. It is a bad idea to base your code on the assumption that someone else doesn't mess with Array.prototype.
Ex.
//Someplace else in your page
Array.prototype.blah = function() {alert(this.length);}
var a = [1,2,3], i;
for (i in a){
console.log(i);
}
//output
1
2
3
blah
3: The first snippet is the slowest because it is doing both a document.getElementById
and an append
inside the loop. That's just plain wrong.
The second snippet is better because it is doing the DOM manipulation once. But it seems jQuery does a lot of work for each parent level element in the markup, appending each of them to a documentFragment
and then to DOM finally.
The third snippet which only has 1 parent element in the markup is the fastest.