Skip to content

Commit 19ddc1e

Browse files
authored
Merge pull request chuanxshi#156 from georgezafiris/master
For-in loop with object properties' existence check
2 parents 57975d5 + fbdd254 commit 19ddc1e

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

general-patterns/for-in-loops.html

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<!doctype html>
1+
<!doctype html>
22
<html lang="en">
33
<head>
44
<title>JavaScript Patterns</title>
@@ -9,22 +9,19 @@
99
/* Title: for-in loops
1010
* Description: optimized for-in loops
1111
*/
12-
1312
// the object
1413
var man = {
1514
hands:2,
1615
legs:2,
1716
heads:1
1817
};
19-
2018
// somewhere else in the code
2119
// a method was added to all objects
2220
if (typeof Object.prototype.clone === 'undefined') {
2321
Object.prototype.clone = function () {
2422
};
2523
}
26-
27-
24+
2825
// antipattern
2926
// for-in loop without checking hasOwnProperty()
3027
for (var i in man) {
@@ -37,32 +34,25 @@
3734
* heads : 1
3835
* clone: function()
3936
*/
40-
41-
4237
// preferred 1
4338
for (var i in man) {
4439
if (man.hasOwnProperty(i)) { // filter
4540
console.log(i, ":", man[i]);
4641
}
4742
}
48-
4943
/*
5044
* result in the console
5145
* hands : 2
5246
* legs : 2
5347
* heads : 1
5448
*/
55-
56-
5749
// preferred 2
5850
// benefit is you can avoid naming collisions in case the `man` object has redefined `hasOwnProperty`
5951
for (var i in man) {
6052
if (Object.prototype.hasOwnProperty.call(man, i)) { // filter
6153
console.log(i, ":", man[i]);
6254
}
6355
}
64-
65-
6656
// preferred 3
6757
// use a local variable to "cache" `Object.prototype.hasOwnProperty`
6858
var i,
@@ -72,8 +62,28 @@
7262
console.log(i, ":", man[i]);
7363
}
7464
}
75-
76-
65+
66+
67+
//Preferred 4
68+
/* Check if object has properties before print output
69+
* using Object.keys(obj) and length built ins. A good method for
70+
* not wasting resources and avoiding errors with larger objects
71+
*/
72+
if (Object.keys(man).length > 0){
73+
for (var item in man)
74+
console.log(item,':',man[item]);
75+
} else {
76+
console.log('Empty Object');}
77+
78+
/*
79+
* hands : 2
80+
* legs : 2
81+
* heads : 1
82+
* clone : function() {
83+
* }
84+
*/
85+
86+
7787
// References
7888
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
7989
</script>

0 commit comments

Comments
 (0)