forked from ryanmcdermott/clean-code-javascript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREADME.md
More file actions
Latest commit
2384 lines (1848 loc) · 56.8 KB
/
Copy pathREADME.md
File metadata and controls
2384 lines (1848 loc) · 56.8 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# clean-code-javascript
## TableofContents
1.[Introduction](#introduction)
2.[Variables](#variables)
3.[Functions](#functions)
4.[ObjectsandDataStructures](#objects-and-data-structures)
5.[Classes](#classes)
6.[SOLID](#solid)
7.[Testing](#testing)
8.[Concurrency](#concurrency)
9.[ErrorHandling](#error-handling)
10.[Formatting](#formatting)
11.[Comments](#comments)
12.[Translation](#translation)
## Introduction

Softwareengineeringprinciples,fromRobertC.Martin's book
[_CleanCode_](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),
adaptedforJavaScript.Thisisnotastyleguide.It's a guide to producing
[readable,reusable,andrefactorable](https://github.com/ryanmcdermott/3rs-of-software-architecture)softwareinJavaScript.
Noteveryprinciplehereinhastobestrictlyfollowed,andevenfewerwillbe
universallyagreedupon.Theseareguidelinesandnothingmore,buttheyare
onescodifiedovermanyyearsofcollectiveexperiencebytheauthorsof
_CleanCode_.
Ourcraftofsoftwareengineeringisjustabitover50yearsold,andweare
stilllearningalot.Whensoftwarearchitectureisasoldasarchitecture
itself,maybethenwewillhaveharderrulestofollow.Fornow,letthese
guidelinesserveasatouchstonebywhichtoassessthequalityofthe
JavaScriptcodethatyouandyourteamproduce.
Onemorething: knowingthesewon't immediately make you a better software
developer,andworkingwiththemformanyyearsdoesn't mean you won'tmake
mistakes.Everypieceofcodestartsasafirstdraft,likewetclaygetting
shapedintoitsfinalform.Finally,wechiselawaytheimperfectionswhen
wereviewitwithourpeers.Don't beat yourself up for first drafts that need
improvement.Beatupthecodeinstead!
## **Variables**
### Usemeaningfulandpronounceablevariablenames
**Bad:**
```javascript
const yyyymmdstr = moment().format("YYYY/MM/DD");
```
**Good:**
```javascript
const currentDate = moment().format("YYYY/MM/DD");
```
**[⬆backtotop](#table-of-contents)**
### Usethesamevocabularyforthesametypeofvariable
**Bad:**
```javascript
getUserInfo();
getClientData();
getCustomerRecord();
```
**Good:**
```javascript
getUser();
```
**[⬆backtotop](#table-of-contents)**
### Usesearchablenames
Wewillreadmorecodethanwewilleverwrite.It's important that the code we
dowriteisreadableandsearchable.By_not_namingvariablesthatendup
beingmeaningfulforunderstandingourprogram,wehurtourreaders.
Makeyournamessearchable.Toolslike
[buddy.js](https://github.com/danielstjules/buddy.js)and
[ESLint](https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md)
canhelpidentifyunnamedconstants.
**Bad:**
```javascript
// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);
```
**Good:**
```javascript
// Declare them as capitalized named constants.
const MILLISECONDS_IN_A_DAY = 60 * 60 * 24 * 1000; //86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
```
**[⬆backtotop](#table-of-contents)**
### Useexplanatoryvariables
**Bad:**
```javascript
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
```
**Good:**
```javascript
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
```
**[⬆backtotop](#table-of-contents)**
### AvoidMentalMapping
Explicitisbetterthanimplicit.
**Bad:**
```javascript
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
dispatch(l);
});
```
**Good:**
```javascript
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(location => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
```
**[⬆backtotop](#table-of-contents)**
### Don't add unneeded context
Ifyourclass/objectnametellsyousomething,don'trepeatthatinyour
variablename.
**Bad:**
```javascript
const Car = {
carMake: "Honda",
carModel: "Accord",
carColor: "Blue"
};
function paintCar(car) {
car.carColor = "Red";
}
```
**Good:**
```javascript
const Car = {
make: "Honda",
model: "Accord",
color: "Blue"
};
function paintCar(car) {
car.color = "Red";
}
```
**[⬆backtotop](#table-of-contents)**
### Usedefaultargumentsinsteadofshortcircuitingorconditionals
Defaultargumentsareoftencleanerthanshortcircuiting.Beawarethatifyou
usethem,yourfunctionwillonlyprovidedefaultvaluesfor`undefined`
arguments.Other"falsy"valuessuchas`''`,`""`,`false`,`null`,`0`,and
`NaN`,willnotbereplacedbyadefaultvalue.
**Bad:**
```javascript
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
```
**Good:**
```javascript
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
```
**[⬆backtotop](#table-of-contents)**
## **Functions**
### Functionarguments(2orfewerideally)
Limitingtheamountoffunctionparametersisincrediblyimportantbecauseit
makestestingyourfunctioneasier.Havingmorethanthreeleadstoa
combinatorialexplosionwhereyouhavetotesttonsofdifferentcaseswith
eachseparateargument.
Oneortwoargumentsistheidealcase,andthreeshouldbeavoidedifpossible.
Anythingmorethanthatshouldbeconsolidated.Usually,ifyouhave
morethantwoargumentsthenyourfunctionistryingtodotoomuch.Incases
whereit's not, most of the time a higher-level object will suffice as an
argument.
SinceJavaScriptallowsyoutomakeobjectsonthefly,withoutalotofclass
boilerplate,youcanuseanobjectifyouarefindingyourselfneedinga
lotofarguments.
Tomakeitobviouswhatpropertiesthefunctionexpects,youcanusetheES2015/ES6
destructuringsyntax.Thishasafewadvantages:
1.Whensomeonelooksatthefunctionsignature,it's immediately clear what
propertiesarebeingused.
2.Itcanbeusedtosimulatenamedparameters.
3.Destructuringalsoclonesthespecifiedprimitivevaluesoftheargument
objectpassedintothefunction.Thiscanhelppreventsideeffects.Note:
objectsandarraysthataredestructuredfromtheargumentobjectareNOT
cloned.
4.Linterscanwarnyouaboutunusedproperties,whichwouldbeimpossible
withoutdestructuring.
**Bad:**
```javascript
function createMenu(title, body, buttonText, cancellable) {
// ...
}
createMenu("Foo", "Bar", "Baz", true);
```
**Good:**
```javascript
function createMenu({ title, body, buttonText, cancellable }) {
// ...
}
createMenu({
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
});
```
**[⬆backtotop](#table-of-contents)**
### Functionsshoulddoonething
Thisisbyfarthemostimportantruleinsoftwareengineering.Whenfunctions
domorethanonething,theyarehardertocompose,test,andreasonabout.
Whenyoucanisolateafunctiontojustoneaction,itcanberefactored
easilyandyourcodewillreadmuchcleaner.Ifyoutakenothingelseawayfrom
thisguideotherthanthis,you'll be ahead of many developers.
**Bad:**
```javascript
function emailClients(clients) {
clients.forEach(client => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
```
**Good:**
```javascript
function emailActiveClients(clients) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
```
**[⬆backtotop](#table-of-contents)**
### Functionnamesshouldsaywhattheydo
**Bad:**
```javascript
function addToDate(date, month) {
// ...
}
const date = new Date();
// It's hard to tell from the function name what is added
addToDate(date, 1);
```
**Good:**
```javascript
function addMonthToDate(month, date) {
// ...
}
const date = new Date();
addMonthToDate(1, date);
```
**[⬆backtotop](#table-of-contents)**
### Functionsshouldonlybeonelevelofabstraction
Whenyouhavemorethanonelevelofabstractionyourfunctionisusually
doingtoomuch.Splittingupfunctionsleadstoreusabilityandeasier
testing.
**Bad:**
```javascript
function parseBetterJSAlternative(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
// ...
});
});
const ast = [];
tokens.forEach(token => {
// lex...
});
ast.forEach(node => {
// parse...
});
}
```
**Good:**
```javascript
function parseBetterJSAlternative(code) {
const tokens = tokenize(code);
const syntaxTree = parse(tokens);
syntaxTree.forEach(node => {
// parse...
});
}
function tokenize(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach(REGEX => {
statements.forEach(statement => {
tokens.push(/* ... */);
});
});
return tokens;
}
function parse(tokens) {
const syntaxTree = [];
tokens.forEach(token => {
syntaxTree.push(/* ... */);
});
return syntaxTree;
}
```
**[⬆backtotop](#table-of-contents)**
### Removeduplicatecode
Doyourabsolutebesttoavoidduplicatecode.Duplicatecodeisbadbecauseit
meansthatthere's more than one place to alter something if you need to change
somelogic.
Imagineifyourunarestaurantandyoukeeptrackofyourinventory: allyour
tomatoes,onions,garlic,spices,etc.Ifyouhavemultipleliststhat
youkeepthison,thenallhavetobeupdatedwhenyouserveadishwith
tomatoesinthem.Ifyouonlyhaveonelist,there's only one place to update!
Oftentimesyouhaveduplicatecodebecauseyouhavetwoormoreslightly
differentthings,thatsharealotincommon,buttheirdifferencesforceyou
tohavetwoormoreseparatefunctionsthatdomuchofthesamethings.Removing
duplicatecodemeanscreatinganabstractionthatcanhandlethissetof
differentthingswithjustonefunction/module/class.
Gettingtheabstractionrightiscritical,that's why you should follow the
SOLIDprincipleslaidoutinthe_Classes_section.Badabstractionscanbe
worsethanduplicatecode,sobecareful!Havingsaidthis,ifyoucanmake
agoodabstraction,doit!Don't repeat yourself, otherwise you'llfindyourself
updatingmultipleplacesanytimeyouwanttochangeonething.
**Bad:**
```javascript
function showDeveloperList(developers) {
developers.forEach(developer => {
const expectedSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const githubLink = developer.getGithubLink();
const data = {
expectedSalary,
experience,
githubLink
};
render(data);
});
}
function showManagerList(managers) {
managers.forEach(manager => {
const expectedSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const portfolio = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio
};
render(data);
});
}
```
**Good:**
```javascript
function showEmployeeList(employees) {
employees.forEach(employee => {
const expectedSalary = employee.calculateExpectedSalary();
const experience = employee.getExperience();
const data = {
expectedSalary,
experience
};
switch (employee.type) {
case "manager":
data.portfolio = employee.getMBAProjects();
break;
case "developer":
data.githubLink = employee.getGithubLink();
break;
}
render(data);
});
}
```
**[⬆backtotop](#table-of-contents)**
### SetdefaultobjectswithObject.assign
**Bad:**
```javascript
const menuConfig = {
title: null,
body: "Bar",
buttonText: null,
cancellable: true
};
function createMenu(config) {
config.title = config.title || "Foo";
config.body = config.body || "Bar";
config.buttonText = config.buttonText || "Baz";
config.cancellable =
config.cancellable !== undefined ? config.cancellable : true;
}
createMenu(menuConfig);
```
**Good:**
```javascript
const menuConfig = {
title: "Order",
// User did not include 'body' key
buttonText: "Send",
cancellable: true
};
function createMenu(config) {
let finalConfig = Object.assign(
{
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true
},
config
);
return finalConfig
// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
// ...
}
createMenu(menuConfig);
```
**[⬆backtotop](#table-of-contents)**
### Don't use flags as function parameters
Flagstellyouruserthatthisfunctiondoesmorethanonething.Functionsshoulddoonething.Splitoutyourfunctionsiftheyarefollowingdifferentcodepathsbasedonaboolean.
**Bad:**
```javascript
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
```
**Good:**
```javascript
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
```
**[⬆backtotop](#table-of-contents)**
### AvoidSideEffects(part1)
Afunctionproducesasideeffectifitdoesanythingotherthantakeavaluein
andreturnanothervalueorvalues.Asideeffectcouldbewritingtoafile,
modifyingsomeglobalvariable,oraccidentallywiringallyourmoneytoa
stranger.
Now,youdoneedtohavesideeffectsinaprogramonoccasion.Liketheprevious
example,youmightneedtowritetoafile.Whatyouwanttodoisto
centralizewhereyouaredoingthis.Don'thaveseveralfunctionsandclasses
thatwritetoaparticularfile.Haveoneservicethatdoesit.Oneandonlyone.
Themainpointistoavoidcommonpitfallslikesharingstatebetweenobjects
withoutanystructure,usingmutabledatatypesthatcanbewrittentobyanything,
andnotcentralizingwhereyoursideeffectsoccur.Ifyoucandothis,youwill
behappierthanthevastmajorityofotherprogrammers.
**Bad:**
```javascript
// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
let name = "Ryan McDermott";
function splitIntoFirstAndLastName() {
name = name.split(" ");
}
splitIntoFirstAndLastName();
console.log(name); // ['Ryan', 'McDermott'];
```
**Good:**
```javascript
function splitIntoFirstAndLastName(name) {
return name.split(" ");
}
const name = "Ryan McDermott";
const newName = splitIntoFirstAndLastName(name);
console.log(name); // 'Ryan McDermott';
console.log(newName); // ['Ryan', 'McDermott'];
```
**[⬆backtotop](#table-of-contents)**
### AvoidSideEffects(part2)
InJavaScript,somevaluesareunchangeable(immutable)andsomearechangeable
(mutable).Objectsandarraysaretwokindsofmutablevaluessoit's important
tohandlethemcarefullywhenthey're passed as parameters to a function. A
JavaScriptfunctioncanchangeanobject's properties or alter the contents of
anarraywhichcouldeasilycausebugselsewhere.
Supposethere's a function that accepts an array parameter representing a
shoppingcart.Ifthefunctionmakesachangeinthatshoppingcartarray-
byaddinganitemtopurchase,forexample-thenanyotherfunctionthat
usesthatsame`cart`arraywillbeaffectedbythisaddition.Thatmaybe
great,howeveritcouldalsobebad.Let's imagine a bad situation:
Theuserclicksthe"Purchase"buttonwhichcallsa`purchase`functionthat
spawnsanetworkrequestandsendsthe`cart`arraytotheserver.Because
ofabadnetworkconnection,the`purchase`functionhastokeepretryingthe
request.Now,whatifinthemeantimetheuseraccidentallyclicksan"Add to Cart"
buttononanitemtheydon't actually want before the network request begins?
Ifthathappensandthenetworkrequestbegins,thenthatpurchasefunction
willsendtheaccidentallyaddeditembecausethe`cart`arraywasmodified.
Agreatsolutionwouldbeforthe`addItemToCart`functiontoalwaysclonethe
`cart`,editit,andreturntheclone.Thiswouldensurethatfunctionsthatarestill
usingtheoldshoppingcartwouldn't be affected by the changes.
Twocaveatstomentiontothisapproach:
1.Theremightbecaseswhereyouactuallywanttomodifytheinputobject,
butwhenyouadoptthisprogrammingpracticeyouwillfindthatthosecases
areprettyrare.Mostthingscanberefactoredtohavenosideeffects!
2.Cloningbigobjectscanbeveryexpensiveintermsofperformance.Luckily,
thisisn't a big issue in practice because there are
[greatlibraries](https://facebook.github.io/immutable-js/)thatallow
thiskindofprogrammingapproachtobefastandnotasmemoryintensiveas
itwouldbeforyoutomanuallycloneobjectsandarrays.
**Bad:**
```javascript
const addItemToCart = (cart, item) => {
cart.push({ item, date: Date.now() });
};
```
**Good:**
```javascript
const addItemToCart = (cart, item) => {
return [...cart, { item, date: Date.now() }];
};
```
**[⬆backtotop](#table-of-contents)**
### Don't write to global functions
PollutingglobalsisabadpracticeinJavaScriptbecauseyoucouldclashwithanother
libraryandtheuserofyourAPIwouldbenone-the-wiseruntiltheygetan
exceptioninproduction.Let's think about an example: what if you wanted to
extendJavaScript's native Array method to have a `diff` method that could
showthedifferencebetweentwoarrays? Youcouldwriteyournewfunction
tothe`Array.prototype`,butitcouldclashwithanotherlibrarythattried
todothesamething.Whatifthatotherlibrarywasjustusing`diff`tofind
thedifferencebetweenthefirstandlastelementsofanarray? Thisiswhyit
wouldbemuchbettertojustuseES2015/ES6classesandsimplyextendthe`Array`global.
**Bad:**
```javascript
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
};
```
**Good:**
```javascript
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter(elem => !hash.has(elem));
}
}
```
**[⬆backtotop](#table-of-contents)**
### Favorfunctionalprogrammingoverimperativeprogramming
JavaScriptisn't a functional language in the way that Haskell is, but it has
afunctionalflavortoit.Functionallanguagescanbecleanerandeasiertotest.
Favorthisstyleofprogrammingwhenyoucan.
**Bad:**
```javascript
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500
},
{
name: "Suzie Q",
linesOfCode: 1500
},
{
name: "Jimmy Gosling",
linesOfCode: 150
},
{
name: "Gracie Hopper",
linesOfCode: 1000
}
];
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
```
**Good:**
```javascript
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500
},
{
name: "Suzie Q",
linesOfCode: 1500
},
{
name: "Jimmy Gosling",
linesOfCode: 150
},
{
name: "Gracie Hopper",
linesOfCode: 1000
}
];
const totalOutput = programmerOutput.reduce(
(totalLines, output) => totalLines + output.linesOfCode,
0
);
```
**[⬆backtotop](#table-of-contents)**
### Encapsulateconditionals
**Bad:**
```javascript
if (fsm.state === "fetching" && isEmpty(listNode)) {
// ...
}
```
**Good:**
```javascript
function shouldShowSpinner(fsm, listNode) {
return fsm.state === "fetching" && isEmpty(listNode);
}
if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
// ...
}
```
**[⬆backtotop](#table-of-contents)**
### Avoidnegativeconditionals
**Bad:**
```javascript
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}
```
**Good:**
```javascript
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}
```
**[⬆backtotop](#table-of-contents)**
### Avoidconditionals
Thisseemslikeanimpossibletask.Uponfirsthearingthis,mostpeoplesay,
"how am I supposed to do anything without an `if` statement?"Theansweristhat
youcanusepolymorphismtoachievethesametaskinmanycases.Thesecond
questionisusually,"well that's great but why would I want to do that?"The
answerisapreviouscleancodeconceptwelearned: afunctionshouldonlydo
onething.Whenyouhaveclassesandfunctionsthathave`if`statements,you
aretellingyouruserthatyourfunctiondoesmorethanonething.Remember,
justdoonething.
**Bad:**
```javascript
class Airplane {
// ...
getCruisingAltitude() {
switch (this.type) {
case "777":
return this.getMaxAltitude() - this.getPassengerCount();
case "Air Force One":
return this.getMaxAltitude();
case "Cessna":
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
}
```
**Good:**
```javascript
class Airplane {
// ...
}
class Boeing777 extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getPassengerCount();
}
}
class AirForceOne extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude();
}
}
class Cessna extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
```
**[⬆backtotop](#table-of-contents)**
### Avoidtype-checking(part1)
JavaScriptisuntyped,whichmeansyourfunctionscantakeanytypeofargument.
Sometimesyouarebittenbythisfreedomanditbecomestemptingtodo
type-checkinginyourfunctions.Therearemanywaystoavoidhavingtodothis.
ThefirstthingtoconsiderisconsistentAPIs.
**Bad:**
```javascript
function travelToTexas(vehicle) {
if (vehicle instanceof Bicycle) {
vehicle.pedal(this.currentLocation, new Location("texas"));
} else if (vehicle instanceof Car) {
vehicle.drive(this.currentLocation, new Location("texas"));
}
}
```
**Good:**
```javascript
function travelToTexas(vehicle) {
vehicle.move(this.currentLocation, new Location("texas"));
}
```
**[⬆backtotop](#table-of-contents)**
### Avoidtype-checking(part2)
Ifyouareworkingwithbasicprimitivevalueslikestringsandintegers,
andyoucan't use polymorphism but you still feel the need to type-check,
youshouldconsiderusingTypeScript.Itisanexcellentalternativetonormal
JavaScript,asitprovidesyouwithstatictypingontopofstandardJavaScript
syntax.Theproblemwithmanuallytype-checkingnormalJavaScriptisthat
doingitwellrequiressomuchextraverbiagethatthefaux"type-safety"youget
doesn't make up for the lost readability. Keep your JavaScript clean, write
goodtests,andhavegoodcodereviews.Otherwise,doallofthatbutwith
TypeScript(which,likeIsaid,isagreatalternative!).
**Bad:**
```javascript
function combine(val1, val2) {
if (
(typeof val1 === "number" && typeof val2 === "number") ||
(typeof val1 === "string" && typeof val2 === "string")
) {
return val1 + val2;
}
throw new Error("Must be of type String or Number");
}
```
**Good:**
```javascript
function combine(val1, val2) {
return val1 + val2;
}
```
**[⬆backtotop](#table-of-contents)**
### Don't over-optimize
Modernbrowsersdoalotofoptimizationunder-the-hoodatruntime.Alotof
times,ifyouareoptimizingthenyouarejustwastingyourtime.[Therearegood
resources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers)
forseeingwhereoptimizationislacking.Targetthoseinthemeantime,until
theyarefixediftheycanbe.
**Bad:**
```javascript
// On old browsers, each iteration with uncached `list.length` would be costly
// because of `list.length` recomputation. In modern browsers, this is optimized.
for (let i = 0, len = list.length; i < len; i++) {
// ...
}
```
**Good:**
```javascript
for (let i = 0; i < list.length; i++) {
// ...
}