@@ -79,35 +79,38 @@ can help identify unnamed constants.
79
79
80
80
** Bad:**
81
81
``` javascript
82
- // What the heck is 525600 for?
83
- for (let i = 0 ; i < 525600 ; i++ ) {
84
- runCronJob ();
85
- }
82
+ // What the heck is 86400 for?
83
+ setTimeout (() => {
84
+ this .blastOff ()
85
+ }, 86400 );
86
+
86
87
```
87
88
88
89
** Good** :
89
90
``` javascript
90
91
// Declare them as capitalized `const` globals.
91
- const MINUTES_IN_A_YEAR = 525600 ;
92
- for (let i = 0 ; i < MINUTES_IN_A_YEAR ; i++ ) {
93
- runCronJob ();
94
- }
92
+ const SECONDS_IN_A_DAY = 86400 ;
93
+
94
+ setTimeout (() => {
95
+ this .blastOff ()
96
+ }, SECONDS_IN_A_DAY );
97
+
95
98
```
96
99
** [ ⬆ back to top] ( #table-of-contents ) **
97
100
98
101
### Use explanatory variables
99
102
** Bad:**
100
103
``` javascript
101
- const cityStateRegex = / ^ (. + )[,\\ s] + (. +? )\s * (\d {5} )? $ / ;
102
- saveCityState (cityStateRegex .match (cityStateRegex)[1 ], cityStateRegex .match (cityStateRegex)[2 ]);
104
+ const address = ' One Infinite Loop, Cupertino 95014' ;
105
+ const cityStateRegex = / ^ [^ ,\\ ] + [,\\ \s ] + (. +? )\s * (\d {5} )? $ / ;
106
+ saveCityState (address .match (cityStateRegex)[1 ], address .match (cityStateRegex)[2 ]);
103
107
```
104
108
105
109
** Good** :
106
110
``` javascript
107
- const cityStateRegex = / ^ (. + )[,\\ s] + (. +? )\s * (\d {5} )? $ / ;
108
- const match = cityStateRegex .match (cityStateRegex)
109
- const city = match[1 ];
110
- const state = match[2 ];
111
+ const address = ' One Infinite Loop, Cupertino 95014' ;
112
+ const cityStateRegex = / ^ [^ ,\\ ] + [,\\ \s ] + (. +? )\s * (\d {5} )? $ / ;
113
+ const [, city , state ] = address .match (cityStateRegex);
111
114
saveCityState (city, state);
112
115
```
113
116
** [ ⬆ back to top] ( #table-of-contents ) **
@@ -174,25 +177,23 @@ function paintCar(car) {
174
177
```
175
178
** [ ⬆ back to top] ( #table-of-contents ) **
176
179
177
- ### Short-circuiting is cleaner than conditionals
180
+ ### Use default arguments instead of short circuiting or conditionals
178
181
179
182
** Bad:**
180
183
``` javascript
181
184
function createMicrobrewery (name ) {
182
- let breweryName;
183
- if (name) {
184
- breweryName = name;
185
- } else {
186
- breweryName = ' Hipster Brew Co.' ;
187
- }
185
+ const breweryName = name || ' Hipster Brew Co.' ;
186
+ ...
188
187
}
188
+
189
189
```
190
190
191
191
** Good** :
192
192
``` javascript
193
- function createMicrobrewery (name ) {
194
- const breweryName = name || ' Hipster Brew Co. '
193
+ function createMicrobrewery (breweryName = ' Hipster Brew Co. ' ) {
194
+ ...
195
195
}
196
+
196
197
```
197
198
** [ ⬆ back to top] ( #table-of-contents ) **
198
199
@@ -227,7 +228,7 @@ const menuConfig = {
227
228
body: ' Bar' ,
228
229
buttonText: ' Baz' ,
229
230
cancellable: true
230
- }
231
+ };
231
232
232
233
function createMenu (config ) {
233
234
// ...
@@ -292,7 +293,7 @@ function addMonthToDate(month, date) {
292
293
}
293
294
294
295
const date = new Date ();
295
- addMonthToDate (date, 1 );
296
+ addMonthToDate (1 , date );
296
297
```
297
298
** [ ⬆ back to top] ( #table-of-contents ) **
298
299
@@ -313,7 +314,7 @@ function parseBetterJSAlternative(code) {
313
314
REGEXES .forEach ((REGEX ) => {
314
315
statements .forEach ((statement ) => {
315
316
// ...
316
- })
317
+ });
317
318
});
318
319
319
320
const ast = [];
@@ -323,7 +324,7 @@ function parseBetterJSAlternative(code) {
323
324
324
325
ast .forEach ((node ) => {
325
326
// parse...
326
- })
327
+ });
327
328
}
328
329
```
329
330
@@ -339,7 +340,7 @@ function tokenize(code) {
339
340
REGEXES .forEach ((REGEX ) => {
340
341
statements .forEach ((statement ) => {
341
342
tokens .push ( /* ... */ );
342
- })
343
+ });
343
344
});
344
345
345
346
return tokens;
@@ -359,7 +360,7 @@ function parseBetterJSAlternative(code) {
359
360
const ast = lexer (tokens);
360
361
ast .forEach ((node ) => {
361
362
// parse...
362
- })
363
+ });
363
364
}
364
365
```
365
366
** [ ⬆ back to top] ( #table-of-contents ) **
@@ -431,25 +432,6 @@ function showList(employees) {
431
432
```
432
433
** [ ⬆ back to top] ( #table-of-contents ) **
433
434
434
- ### Use default arguments instead of short circuiting
435
- ** Bad:**
436
- ``` javascript
437
- function writeForumComment (subject , body ) {
438
- subject = subject || ' No Subject' ;
439
- body = body || ' No text' ;
440
- }
441
-
442
- ```
443
-
444
- ** Good** :
445
- ``` javascript
446
- function writeForumComment (subject = ' No subject' , body = ' No text' ) {
447
- // ...
448
- }
449
-
450
- ```
451
- ** [ ⬆ back to top] ( #table-of-contents ) **
452
-
453
435
### Set default objects with Object.assign
454
436
455
437
** Bad:**
@@ -459,12 +441,12 @@ const menuConfig = {
459
441
body: ' Bar' ,
460
442
buttonText: null ,
461
443
cancellable: true
462
- }
444
+ };
463
445
464
446
function createMenu (config ) {
465
- config .title = config .title || ' Foo'
466
- config .body = config .body || ' Bar'
467
- config .buttonText = config .buttonText || ' Baz'
447
+ config .title = config .title || ' Foo' ;
448
+ config .body = config .body || ' Bar' ;
449
+ config .buttonText = config .buttonText || ' Baz' ;
468
450
config .cancellable = config .cancellable === undefined ? config .cancellable : true ;
469
451
470
452
}
@@ -479,7 +461,7 @@ const menuConfig = {
479
461
// User did not include 'body' key
480
462
buttonText: ' Send' ,
481
463
cancellable: true
482
- }
464
+ };
483
465
484
466
function createMenu (config ) {
485
467
config = Object .assign ({
@@ -561,7 +543,7 @@ function splitIntoFirstAndLastName(name) {
561
543
return name .split (' ' );
562
544
}
563
545
564
- const name = ' Ryan McDermott'
546
+ const name = ' Ryan McDermott' ;
565
547
const newName = splitIntoFirstAndLastName (name);
566
548
567
549
console .log (name); // 'Ryan McDermott';
@@ -597,7 +579,7 @@ Array.prototype.diff = function diff(comparisonArray) {
597
579
}
598
580
599
581
return values;
600
- }
582
+ };
601
583
```
602
584
603
585
** Good:**
@@ -903,13 +885,13 @@ using getters and setters to access data on objects is far better than simply
903
885
looking for a property on an object. "Why?" you might ask. Well, here's an
904
886
unorganized list of reasons why:
905
887
906
- 1 . When you want to do more beyond getting an object property, you don't have
888
+ * When you want to do more beyond getting an object property, you don't have
907
889
to look up and change every accessor in your codebase.
908
- 2 . Makes adding validation simple when doing a ` set ` .
909
- 3 . Encapsulates the internal representation.
910
- 4 . Easy to add logging and error handling when getting and setting.
911
- 5 . Inheriting this class, you can override default functionality.
912
- 6 . You can lazy load your object's properties, let's say getting it from a
890
+ * Makes adding validation simple when doing a ` set ` .
891
+ * Encapsulates the internal representation.
892
+ * Easy to add logging and error handling when getting and setting.
893
+ * Inheriting this class, you can override default functionality.
894
+ * You can lazy load your object's properties, let's say getting it from a
913
895
server.
914
896
915
897
@@ -940,11 +922,11 @@ class BankAccount {
940
922
this ._balance = amount;
941
923
}
942
924
}
943
-
925
+
944
926
get balance () {
945
927
return this ._balance ;
946
928
}
947
-
929
+
948
930
verifyIfAmountCanBeSetted (val ) {
949
931
// ...
950
932
}
@@ -970,11 +952,11 @@ This can be accomplished through closures (for ES5 and below).
970
952
971
953
const Employee = function (name ) {
972
954
this .name = name;
973
- }
955
+ };
974
956
975
957
Employee .prototype .getName = function getName () {
976
958
return this .name ;
977
- }
959
+ };
978
960
979
961
const employee = new Employee (' John Doe' );
980
962
console .log (` Employee name: ${ employee .getName ()} ` ); // Employee name: John Doe
@@ -1044,7 +1026,7 @@ class UserAuth {
1044
1026
class UserSettings {
1045
1027
constructor (user ) {
1046
1028
this .user = user;
1047
- this .auth = new UserAuth (user)
1029
+ this .auth = new UserAuth (user);
1048
1030
}
1049
1031
1050
1032
changeSettings (settings ) {
@@ -1163,7 +1145,7 @@ function renderLargeRectangles(rectangles) {
1163
1145
rectangle .setHeight (5 );
1164
1146
const area = rectangle .getArea (); // BAD: Will return 25 for Square. Should be 20.
1165
1147
rectangle .render (area);
1166
- })
1148
+ });
1167
1149
}
1168
1150
1169
1151
const rectangles = [new Rectangle (), new Rectangle (), new Square ()];
@@ -1232,7 +1214,7 @@ function renderLargeShapes(shapes) {
1232
1214
1233
1215
const area = shape .getArea ();
1234
1216
shape .render (area);
1235
- })
1217
+ });
1236
1218
}
1237
1219
1238
1220
const shapes = [new Rectangle (), new Rectangle (), new Square ()];
@@ -1523,7 +1505,7 @@ class Car {
1523
1505
const car = new Car ();
1524
1506
car .setColor (' pink' );
1525
1507
car .setMake (' Ford' );
1526
- car .setModel (' F-150' )
1508
+ car .setModel (' F-150' );
1527
1509
car .save ();
1528
1510
```
1529
1511
@@ -1721,9 +1703,9 @@ require('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', (req
1721
1703
} else {
1722
1704
console .log (' File written' );
1723
1705
}
1724
- })
1706
+ });
1725
1707
}
1726
- })
1708
+ });
1727
1709
1728
1710
```
1729
1711
@@ -1738,7 +1720,7 @@ require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Marti
1738
1720
})
1739
1721
.catch ((err ) => {
1740
1722
console .error (err);
1741
- })
1723
+ });
1742
1724
1743
1725
```
1744
1726
** [ ⬆ back to top] ( #table-of-contents ) **
@@ -1761,15 +1743,15 @@ require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Marti
1761
1743
})
1762
1744
.catch ((err ) => {
1763
1745
console .error (err);
1764
- })
1746
+ });
1765
1747
1766
1748
```
1767
1749
1768
1750
** Good** :
1769
1751
``` javascript
1770
1752
async function getCleanCodeArticle () {
1771
1753
try {
1772
- const request = await require (' request-promise' )
1754
+ const request = await require (' request-promise' );
1773
1755
const response = await request .get (' https://en.wikipedia.org/wiki/Robert_Cecil_Martin' );
1774
1756
const fileHandle = await require (' fs-promise' );
1775
1757
@@ -2093,7 +2075,7 @@ $scope.model = {
2093
2075
// //////////////////////////////////////////////////////////////////////////////
2094
2076
const actions = function () {
2095
2077
// ...
2096
- }
2078
+ };
2097
2079
```
2098
2080
2099
2081
** Good** :
@@ -2105,6 +2087,6 @@ $scope.model = {
2105
2087
2106
2088
const actions = function () {
2107
2089
// ...
2108
- }
2090
+ };
2109
2091
```
2110
2092
** [ ⬆ back to top] ( #table-of-contents ) **
0 commit comments