File tree Expand file tree Collapse file tree 1 file changed +24
-14
lines changed
Expand file tree Collapse file tree 1 file changed +24
-14
lines changed Original file line number Diff line number Diff line change 1- <!doctype html>
1+ <!doctype html>
22< html lang ="en ">
33< head >
44< title > JavaScript Patterns</ title >
99/* Title: for-in loops
1010 * Description: optimized for-in loops
1111 */
12-
1312// the object
1413var man = {
1514hands :2 ,
1615legs :2 ,
1716heads :1
1817} ;
19-
2018// somewhere else in the code
2119// a method was added to all objects
2220if ( typeof Object . prototype . clone === 'undefined' ) {
2321Object . prototype . clone = function ( ) {
2422} ;
2523}
26-
27-
24+
2825// antipattern
2926// for-in loop without checking hasOwnProperty()
3027for ( var i in man ) {
3734 * heads : 1
3835 * clone: function()
3936 */
40-
41-
4237// preferred 1
4338for ( var i in man ) {
4439if ( man . hasOwnProperty ( i ) ) { // filter
4540console . 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`
5951for ( var i in man ) {
6052if ( Object . prototype . hasOwnProperty . call ( man , i ) ) { // filter
6153console . log ( i , ":" , man [ i ] ) ;
6254}
6355}
64-
65-
6656// preferred 3
6757// use a local variable to "cache" `Object.prototype.hasOwnProperty`
6858var i ,
7262console . 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 >
You can’t perform that action at this time.
0 commit comments