-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript style guide.html
1492 lines (1185 loc) · 40.2 KB
/
javascript style guide.html
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
<!DOCTYPE html>
<html>
<head>
<title>javascript style guide</title>
<link rel="stylesheet" type="text/css" href="./CSS/home.css">
<style></style>
</head>
<body>
<H1>javascript style guide</H1>
<div id="container"></div>
<div id="footer">
<h3> Document Information </h3>
<ul>
<li>
Date: 2015/04/10
</li>
<li>
Reference:
<ul>
<li><a target="_blank" href="https://github.com/airbnb/javascript#chat-with-us-about-javascript">chat with us about javascript</a></li>
</ul>
</li>
</ul>
</div>
</body>
</html>
<script src="./LIB/jquery/jquery-2.1.3.js"></script>
<script src="./LIB/home.js"></script>
<script type="text/javascript">
/* Type
Primitives: When you access a primitive type you work directly on its value.
string
number
boolean
null
undefined
Complex: When you access a complex type you work on a reference to its value.
object
array
function
*/
(function(){
try{
var foo = 1;
var bar = foo;
bar = 9;
console.log(foo, bar); // => 1, 9
var foo2 = [1, 2];
var bar2 = foo2;
bar2[0] = 9;
console.log(foo2[0], bar2[0]); // => 9, 9
}catch(e){
console.error(e.message);
}
}());
/*
Objects
Use the literal syntax for object creation.
Don't use reserved words as keys. It won't work in IE8
Use readable synonyms in place of reserved words.
*/
(function(){
try{
//Use the literal syntax for object creation.
// bad
var item = new Object();
// good
var item = {};
//Don't use reserved words as keys. It won't work in IE8.
// bad
var superman = {
default: { clark: 'kent' },
private: true
};
// good
var superman = {
defaults: { clark: 'kent' },
hidden: true
};
//Use readable synonyms in place of reserved words.
// bad
var superman = {
class: 'alien'
};
// bad
var superman = {
klass: 'alien'
};
// good
var superman = {
type: 'alien'
};
}catch(e){
console.error(e.message);
}
}());
/*
Arrays
Use the literal syntax for array creation.
Use Array#push instead of direct assignment to add items to an array.
When you need to copy an array use Array#slice.
To convert an array-like object to an array, use Array#slice.
*/
(function(){
try{
//Use the literal syntax for array creation.
// bad
var items = new Array();
// good
var items = [];
//Use Array#push instead of direct assignment to add items to an array.
var someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';
// good
someStack.push('abracadabra');
//When you need to copy an array use Array#slice.
var len = items.length;
var itemsCopy = [];
var i;
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
//To convert an array-like object to an array, use Array#slice.
function trigger() {
var args = Array.prototype.slice.call(arguments);
//...
}
}catch(e){
console.error(e.message);
}
}());
/*
Strings
Use single quotes '' for strings.
Strings longer than 80 characters should be written across multiple lines using string concatenation.
When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE
*/
(function(){
try{
//Use single quotes '' for strings.
// bad
var name = "Bob Parr";
// good
var name = 'Bob Parr';
// bad
var fullName = "Bob " + this.lastName;
// good
var fullName = 'Bob ' + this.lastName;
//Strings longer than 80 characters should be written across multiple lines using string concatenation.
//Note: If overused, long strings with concatenation could impact performance.
// bad
var errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';
// bad
var errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';
// good
var errorMessage = 'This is a super long error that was thrown because ' +
'of Batman. When you stop to think about how Batman had anything to do ' +
'with this, you would get nowhere fast.';
//When programmatically building up a string, use Array#join instead of string concatenation. Mostly for IE.
var items;
var messages;
var length;
var i;
messages = [{
state: 'success',
message: 'This one worked.'
}, {
state: 'success',
message: 'This one worked as well.'
}, {
state: 'error',
message: 'This one did not work.'
}];
length = messages.length;
// bad
function inbox1(messages) {
items = 'start: ';
for (i = 0; i < length; i++) {
items += ' No.' + (i + 1) + ': ' + messages[i].message;
}
items += ' end.';
return items;
}
// good
function inbox2(messages) {
items = [];
for (i = 0; i < length; i++) {
items[i] = ' No.' + (i + 1) + ': ' + messages[i].message;
}
return 'start: ' + items.join('') + ' end.';
}
console.log(inbox1(messages));
console.log(inbox2(messages));
}catch(e){
console.error(e.message);
}
}());
/*
Functions
Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
ECMA-262 defines a block as a list of statements. A function declaration is not a statement.
Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
*/
(function(){
try{
//Function expressions:
// anonymous function expression
var anonymous = function() {
return true;
};
// named function expression
var named = function named() {
return true;
};
// immediately-invoked function expression (IIFE)
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears.
//Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. Read ECMA-262's note on this issue.
// bad
if (true) {
function test() {
console.log('Nope.');
}
}
// good
var test;
if (true) {
test = function test() {
console.log('Yup.');
};
}
//Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.
// bad
function nope(name, options, arguments) {
// ...stuff...
}
// good
function yup(name, options, args) {
// ...stuff...
}
}catch(e){
console.error(e.message);
}
}());
/*
Properties
Use dot notation when accessing properties.
Use subscript notation [] when accessing properties with a variable.
*/
(function(){
try{
//Use dot notation when accessing properties.
var luke = {
jedi: true,
age: 28
};
// bad
var isJedi = luke['jedi'];
// good
var isJedi = luke.jedi;
//Use subscript notation [] when accessing properties with a variable.
var luke = {
jedi: true,
age: 28
};
function getProp(prop) {
return luke[prop];
}
var isJedi = getProp('jedi');
console.log("Code snippet2");
}catch(e){
console.error(e.message);
}
}());
/*
Variables
Always use var to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
Use one var declaration per variable. It's easier to add new variable declarations this way, and you never have to worry about swapping out a ; for a , or introducing punctuation-only diffs.
Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
*/
(function(){
try{
//Always use var to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that.
function SuperPower(){
}
// bad
superPower = new SuperPower();
// good
var superPower = new SuperPower();
//Use one var declaration per variable. It's easier to add new variable declarations this way, and you never have to worry about swapping out a ; for a , or introducing punctuation-only diffs.
function getItems(){
return 'a';
}
// bad
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';
// bad
// (compare to above, and try to spot the mistake)
var items = getItems(),
goSportsTeam = true;
dragonball = 'z';
// good
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
//Declare unassigned variables last. This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
// bad
var i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
var i;
var items = getItems();
var dragonball;
var goSportsTeam = true;
var len;
// good
var items = getItems();
var goSportsTeam = true;
var dragonball;
var length;
var i;
//Assign variables at the top of their scope. This helps avoid issues with variable declaration and assignment hoisting related issues.
// bad
function a(){
test();
console.log('doing stuff..');
//..other stuff..
var name = getName();
if (name === 'test') {
return false;
}
return name;
}
// good
function d(){
var name = getName();
test();
console.log('doing stuff..');
//..other stuff..
if (name === 'test') {
return false;
}
return name;
}
// bad
function b(){
var name = getName();
if (!arguments.length) {
return false;
}
return true;
}
// good
function c(){
if (!arguments.length) {
return false;
}
var name = getName();
return true;
}
console.log("Code snippet2");
}catch(e){
console.error(e.message);
}
}());
/*
Hoisting
Variable declarations get hoisted to the top of their scope, but their assignment does not.
Anonymous function expressions hoist their variable name, but not the function assignment.
Named function expressions hoist the variable name, not the function name or the function body.
Function declarations hoist their name and the function body.
*/
(function(){
try{
// we know this wouldn't work (assuming there
// is no notDefined global variable)
function example() {
console.log(notDefined); // => throws a ReferenceError
}
// creating a variable declaration after you
// reference the variable will work due to
// variable hoisting. Note: the assignment
// value of `true` is not hoisted.
function example() {
console.log(declaredButNotAssigned); // => undefined
var declaredButNotAssigned = true;
}
// The interpreter is hoisting the variable
// declaration to the top of the scope,
// which means our example could be rewritten as:
function example() {
var declaredButNotAssigned;
console.log(declaredButNotAssigned); // => undefined
declaredButNotAssigned = true;
}
}catch(e){
console.error(e.message);
}
}());
(function(){
try{
function example() {
console.log(anonymous); // => undefined
anonymous(); // => TypeError anonymous is not a function
var anonymous = function() {
console.log('anonymous function expression');
};
}
}catch(e){
console.error(e.message);
}
}());
(function(){
try{
function example() {
console.log(named); // => undefined
named(); // => TypeError named is not a function
superPower(); // => ReferenceError superPower is not defined
var named = function superPower() {
console.log('Flying');
};
}
// the same is true when the function name
// is the same as the variable name.
function example() {
console.log(named); // => undefined
named(); // => TypeError named is not a function
var named = function named() {
console.log('named');
}
}
}catch(e){
console.error(e.message);
}
}());
(function(){
try{
function example() {
superPower(); // => Flying
function superPower() {
console.log('Flying');
}
}
}catch(e){
console.error(e.message);
}
}());
/*
Comparison Operators & Equality
Use === and !== over == and !=.
Comparison operators are evaluated using coercion with the ToBoolean method and always follow these simple rules:
Objects evaluate to true
Undefined evaluates to false
Null evaluates to false
Booleans evaluate to the value of the boolean
Numbers evaluate to false if +0, -0, or NaN, otherwise true
Strings evaluate to false if an empty string '', otherwise true
Use shortcuts.
*/
(function(){
try{
var name = 'a';
var collection = ['a','b','c'];
if ([0]) {
// true
// An array is an object, objects evaluate to true
}
// bad
if (name !== '') {
// ...stuff...
}
// good
if (name) {
// ...stuff...
}
// bad
if (collection.length > 0) {
// ...stuff...
}
// good
if (collection.length) {
// ...stuff...
}
}catch(e){
console.error(e.message);
}
}());
/*
Blocks
Use braces with all multi-line blocks.
If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace.
*/
(function(){
try{
var test = true;
// bad
if (test)
return false;
// good
if (test) return false;
// good
if (test) {
return false;
}
// bad
function a() { return false; }
// good
function b() {
return false;
}
// bad
if (test) {
//do something
}
else {
//do something
}
// good
if (test) {
//do something
} else {
//do something
}
}catch(e){
console.error(e.message);
}
}());
/*
Comments
Use \/** ... *\/ for multi-line comments. Include a description, specify types and values for all parameters and return values.
Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.
Prefixing your comments with FIXME or TODO helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME -- need to figure this out or TODO -- need to implement.
*/
(function(){
try{
// bad
var active = true; // is current tab
// good
// is current tab
var active = true;
// bad
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this._type || 'no type';
return type;
}
// good
function getType() {
console.log('fetching type...');
// set the default type to 'no type'
var type = this._type || 'no type';
return type;
}
function Calculator() {
// FIXME: shouldn't use a global here
total = 0;
return this;
}
function Calculator() {
// TODO: total should be configurable by an options param
this.total = 0;
return this;
}
}catch(e){
console.error(e.message);
}
}());
/*
Whitespace
Use soft tabs set to 2 spaces.
Place 1 space before the leading brace.
Place 1 space before the opening parenthesis in control statements (if, while etc.). Place no space before the argument list in function calls and declarations.
Set off operators with spaces.
End files with a single newline character.
Use indentation when making long method chains. Use a leading dot, which emphasizes that the line is a method call, not a new statement.
Leave a blank line after blocks and before the next statement
*/
/*
Commas
Leading commas: Nope.
Additional trailing comma: Nope. This can cause problems with IE6/7 and IE9 if it's in quirksmode. Also, in some implementations of ES3 would add length to an array if it had an additional trailing comma.
*/
(function(){
try{
var once, upon, aTime;
// bad
var story = [
once
, upon
, aTime
];
// good
var story = [
once,
upon,
aTime
];
// bad
var hero = {
firstName: 'Bob'
, lastName: 'Parr'
, heroName: 'Mr. Incredible'
, superPower: 'strength'
};
// good
var hero = {
firstName: 'Bob',
lastName: 'Parr',
heroName: 'Mr. Incredible',
superPower: 'strength'
};
// bad
var hero = {
firstName: 'Kevin',
lastName: 'Flynn',
};
var heroes = [
'Batman',
'Superman',
];
// good
var hero = {
firstName: 'Kevin',
lastName: 'Flynn'
};
var heroes = [
'Batman',
'Superman'
];
}catch(e){
console.error(e.message);
}
}());
/*
Semicolons
*/
;(function(){
try{
// good (guards against the function becoming an argument when two files with IIFEs are concatenated)
// E.g.
// ;(function() {
// var name = 'Skywalker';
// return name;
// })();
}catch(e){
console.error(e.message);
}
}());
/*
Type Casting & Coercion
Perform type coercion at the beginning of the statement.
Use parseInt for Numbers and always with a radix for type casting.
*/
(function(){
try{
this.reviewScore = 9;
//Strings:
// bad
var totalScore = this.reviewScore + '';
// good
var totalScore = '' + this.reviewScore;
// bad
var totalScore = '' + this.reviewScore + ' total score';
// good
var totalScore = this.reviewScore + ' total score';
//Use parseInt for Numbers and always with a radix for type casting.
var inputValue = '4';
// bad
var val = new Number(inputValue);
// bad
var val = +inputValue;
// bad
var val = inputValue >> 0;
// bad
var val = parseInt(inputValue);
// good
var val = Number(inputValue);
// good
var val = parseInt(inputValue, 10);
//If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons, leave a comment explaining why and what you're doing.
// good
//parseInt was the reason my code was slow.
//Bitshifting the String to coerce it to a
//Number made it a lot faster.
var val = inputValue >> 0;
//Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values, but Bitshift operations always return a 32-bit integer (source). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion. Largest signed 32-bit Int is 2,147,483,647:
2147483647 >> 0 //=> 2147483647
2147483648 >> 0 //=> -2147483648
2147483649 >> 0 //=> -2147483647
//Booleans:
var age = 0;
// bad
var hasAge = new Boolean(age);
// good
var hasAge = Boolean(age);
// good
var hasAge = !!age;
}catch(e){
console.error(e.message);
}
}());
/*
Naming Conventions
Avoid single letter names. Be descriptive with your naming.
Use camelCase when naming objects, functions, and instances.
Use PascalCase when naming constructors or classes.
Use a leading underscore _ when naming private properties.
When saving a reference to this use _this.
Name your functions. This is helpful for stack traces.
If your file exports a single class, your filename should be exactly the name of the class.
*/
(function(){
try{
// bad
function q() {
// ...stuff...
}
// good
function query() {
// ..stuff..
}
// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
function c() {}
var u = new user({
name: 'Bob Parr'
});
// good
var thisIsMyObject = {};
function thisIsMyFunction() {}
var userIns = new User({
name: 'Bob Parr'
});
// bad
function user(options) {
this.name = options.name;
}
var bad = new user({
name: 'nope'
});
// good
function User(options) {
this.name = options.name;
}
var good = new User({
name: 'yup'
});
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
// bad
function fn3() {
var self = this;
return function() {
console.log(self);
};
}
// bad
function fn1() {
var that = this;
return function() {
console.log(that);
};
}
// good
function fn2() {
var _this = this;
return function() {
console.log(_this);
};
}
// bad
var log = function(msg) {
console.log(msg);
};
// good