forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfor-loops.html
More file actions
64 lines (50 loc) · 1.41 KB
/
for-loops.html
File metadata and controls
64 lines (50 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: for loops
* Description: optimized for loops
*/
// sub-optimal loop
for (var i = 0; i < myarray.length; i++) {
// do something with myarray[i]
}
// optimization 1 - cache the length of the array with the use of `max`
for (var i = 0, max = myarray.length; i < max; i++) {
// do something with myarray[i]
}
// optimization 2 - use single var pattern for consistency
// NOTE: A drawback is that it makes it a little harder to copy and paste whole loops while refactoring code.
var i = 0,
max,
myarray = [];
for (i = 0, max = myarray.length; i < max; i++) {
// do something with myarray[i]
}
// optimization 3 - substitute `i++` with `i = i + 1` or `i += 1` to avoid excessive trickiness
var i = 0,
max,
myarray = [];
for (i = 0, max = myarray.length; i < max; i += 1) {
// do something with myarray[i]
}
// preferred 1
var i, myarray = [];
for (i = myarray.length; i--;) {
// do something with myarray[i]
}
// preferred 2
var myarray = [],
i = myarray.length;
while (i--) {
// do something with myarray[i]
}
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>