-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathJavaScript.language.txt
2487 lines (2189 loc) · 154 KB
/
JavaScript.language.txt
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
┏━━━━━━━━━━━━━━━━┓
┃ JAVASCRIPT ┃
┗━━━━━━━━━━━━━━━━┛
VERSION ==> #Standard is called ECMAScript. JavaScript and ActionScript are dialects.
#This doc shows strict mode only
SUPPORT ==> #Use this notation for new features:
~# - stage 3 proposal
NUM# - introduced by Node NUM.*.*
*# - not latest Node
#Only document|use features in stage >= 3
#Can look at support with:
# - EcmaScript kangax compat-table
# - http://node.green/
MAIN PRINCIPLES ==> #Case-sensitive. Whitespaces are ignored.
#Type: weak, dynamic, generic, late/duck.
#Lexical-scope
#Functional (first-class functions)
#Object-oriented (prototype-based)
#Imperative (structures close to C)
#Need a host environnement (e.g. browser) for I/O
#Memory management: garbage collection.
EXECUTION ==> #Each browser has own JavaScript engine, which was in the past interpreted,
#but now is byte-compiled or compiled:
# - V8 (Chrome, Opera 15+, Edge >=2020, Node.js, Deno)
# - SpiderMonkey (Firefox, MongoDB >=3.2)
# - JavaScriptCore/SquirrelFish/Nitro (Safari) part of WebKit
# - Chakra (IE9+, Edge <2019), opensourced at ChakraCore
┌───────────┐
│ ASYNC │
└───────────┘
EVENT LOOP ==> #Loops:
# - each event loop loops through [macro]tasks
# - each macrotask loops through microtasks|tick
# - each microtask is run synchronously
NEW TASKS ==> #Each thread has a single event loop
# - creates a new thread: process, WebWorker, cross-origin <iframe>
#Macrotasks are created by I/O code, which includes:
# - setTimeout|Interval|Immediate()
# - filesystem, network or OS calls
# - not streams on their own
# - event handlers triggered by browser interaction.
# - events triggered directly through JavaScript, which include Node.js EVENTEMITTER, are sync.
#Microtasks are created by:
# - process.nextTick()
# - queueMicrotask()
# - PROMISE.then|catch() callbacks
# - priority:
# - first-in first-out
# - process.nextTick() before other types of microtasks
# - e.g. if a process.nextTick() create a new process.nextTick(),
# it will be fired before pending PROMISE microtasks
PERFORMANCE ==> #For Node.js:
# - minimal time of a macrotask is 1ms.
# I.e. a macrotask that only does setTimeout(..., 0) will last 1ms
# - there is no minimal time for a microtask
SINGLE-THREADED ==> #Each event loop is single-threaded:
# - i.e. only one microtask and one macrotask runs at any time
#Resources:
# - I/O-intensive tasks:
# - are the slowest
# - should yield the thread and be woken up on a new macrotask
# - this is what most I/O functions do by default, i.e. I/O calls are
# optimally handled
# - i.e. developer just need to use async I/O functions
# - CPU-intensive tasks:
# - will hold the whole thread
# - if too slow, should spawn a new thread instead
# - memory consumption:
# - is very low, because thread and processes is what makes memory go high
ASYNC EXPECTATION ==> #Libraries exposing callbacks should trigger them in a new microtask,
#because this what consumers usually expect.
# - e.g. this would otherwise be problematic:
# let VAR = FUNC(CALLBACK); VAR.on('start', ...)
THREAD EXIT ==> #Thread exits when the event loop has no more macrotasks
#In a browser, this never happens, as there are always DOM event listeners.
#In Node.js:
# - timers methods keep the thread alive
# - i.e. automatically ref'd
# - process.nextTick(), queueMicrotask(), setTimeout|setInterval()
# - PROMISEs do not keep the thread alive by themselves
# - PROMISE.then|catch() FUNC, await PROMISE
# - but they do when the PROMISE relies on ref'd logic
# - any external input is ref'd by Node.js
# - I/O, processes, network
# - sometimes ref|unref() methods are exposed to manually control this
ASYNC STACK TRACE ==> #Also called "long stack trace"
#When using async, the callback function does not include stack trace from parent function
# - because it is processed on a different microtask
#This is missing in:
# - setTimeout|Interval|Immediate(FUNC), process.nextTick(FUNC), queueMicrotask()
# - filesystem, network, OS or browser interaction event handlers
# - new Promise()
#This is not missing when using async|await:
# - including whn using Promise.*()
# - supported:
# - code during|before an await statement: always
# - code after an await statement: most browsers and Node
┌───────────┐
│ SCOPE │
└───────────┘
GENERAL ==> # - variable scope is:
# - "var": FUNC {...}
# - "let|const": any {...}
# - any function inherits scope of the function in which it is declared (not called)
# - inherits by reference, not by value
globalThis #Global scope reference
#Otherwise can be in many places (self in WORKER, window in DOM, global in Node.js, this otherwise)
DECLARATION ==> # - using undeclared VAR throws ReferenceError (except with typeof)
# - using VAR (even if declared in parent scope) declared later in
# current scope with:
# - "let|const": throws ReferenceError ("Temporal Dead Zone")
# - "var": adds an implicit empty declaration before, i.e. will be
# undefined (variable hoisting)
# - function FUNC(){}: adds an implicit declaration+assignment before
DECLARING FUNCTIONS ==> # - FUNC = function [FUNC2](){}
# - declared+assigned at runtime (like other variables)
# - this also covers anonymous function, and void function [FUNC2](){}
# - Using "FUNC2":
# - equivalent of doing let FUNC2 = function(){} at the beginning of
# the same function
# - allow recursion to reference themselves without risk of parent
# scope to reassign FUNC2
# - function FUNC2(){}:
# - declared+assigned at parsetime
# - i.e. equivalent of doing let FUNC2 = function () {} at {...} scope
# beginning
# - new Function(...): child of global scope
MEMORY MANAGEMENT ==> #Garbage collection:
# - use tracing, i.e. no problem with reference cycles
# - root objects are global variables
# - closures carry references to their parent scope, but only of the
# references they use
# - this might be problematic when closures are returned, i.e. go up the
# stack, extending their parent scope lifetime
#Memory leak happens with combination of variables being:
# - big, e.g.:
# - functions carrying parent SCOPEs
# - big objects
# - raw data returned from server
# - long-lived, e.g.:
# - attached to top/long-lived SCOPEs, e.g. global variables, e.g.:
# - long-lived DOM elements
# - global functions (e.g. global event handlers, setInterval(), ...)
#Avoiding:
# - unset variables just after being used if they are big or attached to
# long-lived objects
# - "unset": prefer setting empty value than using "delete"
# - only use closures as argument or return value when needed
new WeakRef(OBJ) #Keep a reference to OBJ, without preventing OBJ from being GC'd
#Should not rely:
# - on when|whether GC happens, since this is very variable
# - on it to guess when|whether GC happens
#For example, should not be used for resource cleanup.
#Should only be used as a way to prevent increasing memory usage.
# - e.g. caches or weak maps
# - consider using WeakMap|WeakSet if possible
WEAKREF.deref()->OBJ|undefined #Returns OBJ. undefined if OBJ was GC'd
new FinalizationRegistry
(FUNC(OBJ, VAL)) #Same improper use warnings as WeakRef
FINALIZATION_REGISTRY.register #Calls FUNC(OBJ, VAL) when OBJ is GC'd
(OBJ[, VAL][, VAL2]) #Keeps weak reference to OBJ|VAL2 (does not prevent it from being GC'd)
#Keep strong reference to VAL (i.e. should not be OBJ)
#VAL2 is the one to use with unregister() (can be same as OBJ)
FINALIZATION_REGISTRY.unregister
(VAL2)->BOOL #BOOL is whether it was registered
new ShadowRealm() 18.13.0~#Global environment
--experimental
-shadow-realm <18.13.0~#
SVAL 18.13.0~#Cannot be an OBJ, except for a FUNC providing it does not use OBJ as argument or return value
REALM.importValue
('MDL', 'VAR')->>SVAL 18.13.0~#Like (await import('MDL')).VAR but bound to a REALM
REALM.evaluate 18.13.0~#Like eval('CODE') but bound to a REALM
('CODE')->SVAL 18.13.0~#Each call has its own scope, but share the same global scope
┌──────────────────────┐
│ BASIC STATEMENTS │
└──────────────────────┘
RESERVED WORDS ==> #enum, await, implements, package, protected, public, private, interface,
#static
STATEMENT; #; optional, but recommended in case could be interpreted as multiline
STATEMENT\ #Only required for multiline statements:
# - within a STR
# - if first line could be interpreted as standalone statement.
// COMMENT
/* COMMENT */ #
#!... #Ignored if first non-blank line
"use strict"; #Start strict mode:
# - i.e. strict ES6|ES7 conformance
# - allows faster optimization by browsers
# - not compatible until IE10
#Applies to current and child scopes:
# - child scopes: including nested functions, anonymous functions, eval(),
# new Function(), etc.
# - but not functions declared in different scopes and called in current|child scopes
# - warning: concatenating with other scripts might put them in same scope,
# making them strict too.
# - must be before any statement (otherwise noop)
#Implicit in any ES6 module (i.e. useless), but not in Node.js modules or
#global scripts
#In the web console, can use an anonymous function in order to use strict mode.
QUAL VAR[ = VAL] #Declaration. Default value is undefined.
[, VAR2[ = VAL2]]... #VAR:
# - cannot be a reserved keyword
# - can contain:
# - $
# - any Unicode char with property "ID_Continue":
# - letters-like
# - numbers-like
# - diacretics
# - _
# - U+200C U+200D (zero-width space)
# - can be included as is, or using \u.... or \u{....}
# - first character must be Unicode char with property "ID_Start",
# (i.e. only letters-like) or $ or _
VAR = VAL; #Assignation.
#Returns VAL, so chain possible: VAR = VAR2 = VAL, but means VAR2 is global
[QUAL] [
VAR [= VAL],
... #[QUAL ]VAR = ITERABLE[NUM], ...
[, ...ITERABLE2] #VAL is default value
] = ITERABLE #ITERABLE2 is variadic assignment
[QUAL] { KEY: VAR[ = VAL] } = OBJ #[QUAL ]VAR = OBJ[KEY], ...
#Without 'QUAL', must wrap with ({...} = OBJ)
#VAL is default value
#Can be { KEY: { KEY2: ... } }
#KEY can appear several times with different VAR,
#including { KEY: { KEY2 }, KEY: KEY }
[QUAL] { KEY[ = VAL] } = OBJ #Same as QUAL { KEY: KEY[ = VAL] } = OBJ
QUAL #var|let|const|using
let VAR #Like var VAR, but {} block scoped.
const VAR #Like let VAR but read-only, i.e. throws error on assignments beyond
#declaration
#Is shallow: if OBJ, only OBJ is read-only, not OBJ.VAR
#Is only for current block scope since:
# - function arguments imply new assignment
# - function return value must be assigned to be used as reference
delete OBJ.VAR #Like assigning undefined except:
# - remove key as well
# - cannot be performed if non-configurable
# - can be performed if non-writable
#Note: for ARR[NUM], does not modify length (like assigning undefined)
#Returns true if OBJ (not OBJ.VAR) exists.
void STATEMENT #Same as STATEMENT, but returns undefined
#void 0 is sometimes used to return undefined without risk for shadowing
# - But not needed since shadowing can be caught by linting
eval("STATEMENT...") #Fire STATEMENT... in current scope. Return last STATEMENT return value.
#To avoid.
#If argument non STR, renvoie VAL.
#"VAR = VAL" does not declare anything.
#Can throw SyntaxError or EvalError.
┌────────────────┐
│ STRUCTURES │
└────────────────┘
SINGLE LINE ==> #Block braces can be skipped if only on single next line (to avoid)
VAL #Anything that returns a VAL
EXPR #Anything that could go on a single line of code ending with ;
... #Several EXPR
TEST ? VAL1 : VAL2 #Returns VAL1 or VAL2
VAL && VAL2 #Same as VAL ? VAL : VAL2
VAL || VAL2 #Same as VAL ? VAL2 : VAL
VAL ?? VAL2 #Same as VAL == null ? VAL : VAL2
VAR &&= VAL2 #Same as VAR = VAR && VAL2
VAR ||= VAL2 #Same as VAR = VAR || VAL2
VAR ??= VAL2 #Same as VAR = VAR ?? VAL2
VAL1, VAL2 #Evaluates both, but returns VAL2.
#Use case: in for or while loops.
{ ... } #Creates a scope
(VAL) #To increase precedence.
if (TEST) { ... }
[else if (TEST) { ... }]...
[else { ... }] #
switch (VAL) {
case VAL2: ... [break;] ...
case VAL3: #Use VAL === VAL2
case VAL4: ... [break;] ... #If no break, execute next case (including "default")
[default: ... [break;]] #Case can be empty, meaning several "case" match when any matches.
} #... can be wrapped in { ... }, which creates a scope
for ([EXPR1] ; [TEST] ; [EXPR2])
{ ... } #Same as: EXPR1; while ( TEST ) { ...; EXPR2; }
while (TEST) { ... } #
do { ... } while (TEST) #
for ([QUAL] VAR in OBJ) { ... } #Iterate over keys that are enumerable, excluding SYMs
#OBJ can be ITERATOR.
break [LABEL] #Stop current for|while|switch iteration or (only with LABEL)
#if_else|anonymous block
#Can target a specific for|while|switch iteration by specifying LABEL: before
#it (to avoid), e.g. LABEL: for ... or LABEL: if ...
continue [LABEL] #Same but only current loop, and only for|while
┌───────────┐
│ TYPES │
└───────────┘
TYPING SYSTEM ==> # - weak: no type specified at Declaration
# - generic: native operators accepts any type, since each native type
# transtype to any (except OBJ->undefined|null)
# - dynamic: type is not checked at compile-time nor (since generic) run-time
AVAILABLE TYPES ==> # - simple: number|boolean|string|bigint|symbol|undefined|null
# - object (TYPE): Object and its children
# - native: Object|Array|Number|Boolean|String|Error|...
# - user-defined:
# - host objects: defined by browser (e.g. DOM elements)
typeof VAR #Returns "boolean|string|number|bigint|symbol|undefined|object|function"
#"object": includes null, excludes FUNC
Object.prototype.toString.call #Returns '[object NAME]' where NAME is (in priority order):
(VAL)->STR # - '[object OBJ[Symbol.toStringTag]]'
# - builtin:
# - 'Null|Undefined|Number|String|Boolean|BigInt|Symbol'
# - 'Object'
# - 'Array|[Shared]ArrayBuffer|DataView|[Big][U]Int|FloatNUMArray'
# - '[Async][Generator]Function'
# - 'Arguments'
# - 'RegExp|Date|Error|[Weak]Map|[Weak]Set|WeakRef|Realm'
# - 'Generator'
# - 'Promise'
# - 'Module'
# - 'Intl.*'
# - 'Math|JSON|Intl|Atomics|Reflect': the namespace itself
# - 'global'
# - not: Proxy
# - 'Object'
# (DOM only)
# - 'DOMError' (deprecated), 'DOMException'
┌──────────────┐
│ EQUALITY │
└──────────────┘
VAL == VAL2
VAL != VAL2 #Implicit transtype
VAL === VAL2
VAL !== VAL2 #No implicit transtype
OBJ == OBJ2
OBJ != OBJ2
OBJ === OBJ2
OBJ !== OBJ2 #Same reference
Object.is(VAL, VAL2) #Same as ===, except !Object.is(+0,-0) and Object.is(NaN, NaN)
┌─────────────────┐
│ TRANSTYPING │
└─────────────────┘
IMPLICIT TRANSTYPING ==> #Uses String|Boolean|Number|BigInt|Object(VAL)
EXPLICIT TRANSTYPING ==> #Prefer using String|Boolean|Number|BigInt|Object(VAL).
#Sometimes used (avoid):
# - BOOL: !!VAL
# - NUM: +VAL, VAL*1, VAL/1, ~~VAL, VAL|0, VAL-0
# - STR: VAL + ''
OBJ[Symbol.toPrimitive]('default')#Called when implicit type ambiguous, e.g. VAL + STR or VAL == VAL2
┌───────────────┐
│ UNDEFINED │
└───────────────┘
undefined #Value of:
# - non-declared VAR: throw ReferenceError when used, except with typeof
# - declared but non-assigned VAR (including arguments and return value)
#Global variable, not keyword
# - non-configurable|writable
# - but can be shadowed by local VAR named "undefined"
typeof VAR === 'undefined' #Like VAR === undefined, except no ReferenceError if VAR undeclared
#Should never be necessary:
# - useless in local scopes
# - in global scope, use globalThis.VAR === undefined
┌──────────┐
│ NULL │
└──────────┘
null #Special keyword indicating emptiness
VAL == null #Implicitly transtype to null|undefined, i.e. returns true for both
VAL === null|undefined #No implicit transtype
┌─────────────┐
│ BOOLEAN │
└─────────────┘
true|false #BOOL
!BOOL
BOOL && BOOL2
BOOL || BOOL2
Boolean(VAL)->NUM #Used for explicit|implicit transtyping.
# - STR: '' false, '...' true
# - NUM|BIGINT: 1 true, 0 false
# - undefined|null: false
# - OBJ|SYM: true
┌────────────┐
│ NUMBER │
└────────────┘
NUM #Always double-precision float (binary64)
#Can use TYPED_ARR for single-precision floats or 8|16|32-bits [u]ints
0xNUM
0XNUM #16 radix
0oNUM
0ONUM #8 radix
0bNUM
0BNUM #2 radix
NUM_... #Underscores can be added:
# - they are ignored and meant as separators
# - works with any radix except octals
NUM + - * / % NUM2 #
-NUM #
NUM++ ++NUM NUM-- --NUM #
NUM ** NUM2 #
NUM ~ & ^ | >> << >>> NUM2 #
NUM OP= NUM2 #E.g. NUM += NUM2
NUM < <= > >= NUM2 #
Number(VAL)->NUM #Used for explicit|implicit transtyping:
# - STR:
# - '': 0
# - 'NUM': NUM
# - trims whitespaces
# - others: NaN
# - BOOL: true 1, false 0
# - BIGINT: TypeError
# - can be explicitely converted though
# - in which case, transtyped to [-]Infinity if out-of-bound
# - undefined: NaN
# - null: 0
# - SYM: TypeError
# - OBJ (in priority):
# - OBJ[Symbol.toPrimitive]('number')
# - OBJ.valueOf()
# - NaN
[Number.]parseFloat(VAL)->NUM #Like Number(VAL) but:
# - returns NaN for non-NUM|STR and ''
# - removes trailing non-numerical chars in STR
# - only understands decimal form
[Number.]parseInt(VAL[, NUM])->NUM#Same as [Number.]parseFloat() but:
# - removes decimals
# - understands decimal or hexadecimal form by default.
# - if NUM, forces radix
NUM.toFixed([NUM])->STR #Number of decimal digits.
#Might have exponential notation or not.
#Def|min NUM: 0. Max NUM: 100.
NUM.toExponential([NUM])->STR #Number of decimal digits.
#Always use exponential notation.
#Def|min NUM: 0. Max NUM: 100.
NUM.toPrecision([NUM])->STR #Number of integer+decimal digits, excluding leading decimals zeros if integer is 0
#Might have exponential notation or not.
#Min NUM: 1. Max NUM: 100.
#If no NUM, behaves like NUM.toString()
NUM.toString(RADIX)->STR #
Number.isInteger(NUM) #Does not coerce to NUM
[Number.]NaN #Returned e.g. by √-1, 0/0 or wrong NUM conversion
#Test:
# - NaN !== NaN but Object.is(NaN, NaN)
# - Number.isNaN(VAL): same as Object.is(VAL, NaN)
# - isNaN(VAL): same as Number.isNaN(Number(VAL))
[-]Infinity #Returned e.g. by overflow like 1e400, or 1/0
Number.POSITIVE_INFINITY #Test:
Number.NEGATIVE_INFINITY # - [-]Infinity === [-]Infinity
# - Number.isFinite(VAL): typeof VAL === 'number' && VAL !== [-]Infinity && !Number.isNaN(VAL)
# - isFinite(VAL): same as Number.isFinite(Number(VAL))
Number.MIN_VALUE #Closest to 0 (underflow) (about 5e-324)
Number.MAX_VALUE #After it is Infinity (overflow) (about 2e+308)
Number.MIN|MAX_SAFE_INTEGER #Smallest|highest integer that can be represented as a float precisely
#(about +|-1e16)
Number.isSafeInteger(NUM)->BOOL #Number.isInteger(NUM) && NUM >= Number.MIN_SAFE_INTEGER && NUM <= Number.MAX_SAFE_INTEGER
#Does not coerce to NUM
Number.EPSILON #NUM +|- NUM2 can create small discrepancies, e.g. 0.3 - 0.1 within a
#EPSILON range:
# - When comparing non-integer NUMs, should check NUM-NUM2 < +|-EPSILON
# - about 2e-16
┌────────────┐
│ BIGINT │
└────────────┘
NUMn #BIGINT. Infinite precision integer
#Behaves like NUM:
# - including octal, hex, binary notations
# - including toString(RADIX)
#Exceptions:
# - integer not double:
# - / % round towards 0
# - cannot use >>> nor +NUMn
# - throw on JSON.stringify()
# - has its own typeof, constructor
# - no BIGINT.toFixed|toPrecision|toExponential() (since it is integer)
BigInt(VAL)->NUM #Used for explicit|implicit transtyping.
# - STR|BOOL|OBJ|undefined: like NUM except SyntaxError instead of NaN
# - null|SYM: SyntaxError
# - NUM:
# - implicit: TypeError
# - exception: == === != !== < <= > >=
# - explicit: possible
# - transtyped to [-]Infinity if out-of-bound
BigInt.asUintN|asIntN #Enforce max size NUM bits on NUM2n
(NUM, NUM2n)->NUM2n #On overall, rotate to min|max value (according to NUM)
┌────────────┐
│ STRING │
└────────────┘
"..." #Escapes everything but " newline and \ (including trailing)
'...' #Escapes everything but ' newline and \ (including trailing)
`...${EXPR}...` #"..." + EXPR + "..."
#Escapes everything (including " ' or newline) but ` ${ or \
\CHAR #Any backslash escape can be used except \a, \c et \e
NEWLINE ==> #OS-independent: '\n' is LF, '\r' is CR
#OS-dependent (CR+LF on Windows, LF others): terminal|file I/O
MAX LENGTH ==> #Standard: at most 2**53 - 1, i.e. ~9e15
#Engine-dependent:
# - v8: 2**29 - 24, i.e. ~5e8
# - SpiderMonkey: 2**30 - 2, i.e. ~1e9
# - SquirrelFish: 2**31 - 1, i.e. ~2e9
STR + STR2 #
STR += STR2 #
STR.concat(STR2...) #
STR < <= > >= #Char by char, code unit-wise
String(VAL)->STR #Used for explicit|implicit transtyping:
# - BOOL|NUM|undefined|null: 'BOOL|...'
# - BIGINT: 'NUM' (not 'NUMn')
# - SYM: 'Symbol(VAR)'
# - only with explicit String(SYM) or SYM.toString()
# - OBJ (in priority order):
# - OBJ[Symbol.toPrimitive]('string')
# - OBJ.toString()
# - FUNC|ARR|REGEXP|DATE|ERROR: see own doc
# - OBJ.valueOf()
# - Object.prototype.toString.call(VAL) (see its doc)
FUNC`...` #FUNC(STR_ARR, VAL...)->VAL:
FUNC `...` # - VAL... are each ${EXPR}
# - STR_ARR[.raw][NUM]:
# - each `...` in-between
# - including empty "" at beginning|end if starts|ends with ${EXPR}
# - if "raw", escape backslashes
# - STR_ARR.length === VAL.length + 1
# - special case for invalid backslash sequences (only if FUNC specified):
# - STR is undefined
# - escaped in STR_ARR.raw, e.g. '\\n'
#FUNC can be String.raw(), which concatenates all like normal template,
#except it escape backslashes
STR[NUM] #Read-only. undefined if out of range.
STR.charAt(NUM) #Same except "" if out of range
STR.at(NUM)->'CHAR' #Like STR[NUM] except -NUM is from end, and is not writable
STR.length #Number of characters
STR.match(REGEXP) #Like REGEXP.exec(STR), except that if g flag, returns all matches as ARR
#(or null)
STR.matchAll(REGEXP) #Returns ITERABLETOR that returns successive REGEXP.exec(STR)
#I.e. as opposed to STR.match(), when using a g flag, parenthesis groups and
#indices will be returned too
STR.search(REGEXP) #Like STR.indexOf() but with a REGEXP
STR.starts|endsWith|includes
(STR2[, NUM]) #
STR.replace(REGEXP|STR2, STR3) #Returns STR, replacing REGEXP with STR3, which can contain:
# - $1, etc.: parenthesis group matches
# - $&: full match
# - $`: what's before full match
# - $': what's after full match
# - $$: $ literal
STR.replace(REGEXP|STR2,
FUNC($&, $1..., INDEX, STR)) #Returns STR, replacing REGEXP with FUNC(...)
STR.replaceAll(REGEXP|STR2, STR3)
STR.replaceAll(REGEXP|STR2, #Same as STR.replace(...) but STR2 implies a 'g' flag.
FUNC($&, $1..., INDEX, STR)) #If REGEXP, must have a 'g' flag.
STR.split(REGEXP|STR2[, UINT]) #Returns an ARR, with REGEXP|STR2 being split delimiter.
#If STR2 is '', means between each characters.
#If REGEXP contains parenthesis groups, each is included in ARR between each element.
#If UINT, does ARR.slice(0, UINT)
STR.repeat(NUM) #
OBJ[Symbol.match](...) #Methods to implement to be able to use STR.match(OBJ)
#or STR.startsWith|endsWith|includes(OBJ)
#Implemented by REGEXP
OBJ[Symbol.replace|split](...) #Methods to implement to be able to use STR.replace|split(OBJ).
#Implemented by REGEXP
OBJ[Symbol.search](...) #Methods to implement to be able to use STR.search(OBJ).
#Implemented by REGEXP
STR.toUpper|LowerCase() #
STR.trim() #
STR.trimLeft|Right() #Remove whitespaces (same as /\s/) on left and|or right.
STR.trimStart|End() #Aliases for trimLeft|Right()
STR.padStart|End(NUM[, STR2]) #If STR.length < NUM, prepends|appends STR2 (def: ' ') until STR.length === NUM
STR.[last]indexOf(STR[, NUM])
STR.slice([NUM[, NUM2]]) #Like ARR
STR.substring(NUM[, NUM2]) #Like .slice() except:
# - negative NUM2 -> 0
# - If NUM2 < NUM, swap
STR.substr(NUM[, NUM2]) #Like .slice() except:
# - NUM can be negative (index from end)
# - NUM2 is length, not index
en|decodeURI(STR) #Percent-encode any character not permitted in URIs, i.e. anything but:
# [:alnum:] - . _ ~ ! ' ( ) * # : ? & = + $ ; , / @
#Should be used for full URIs
#Uses UTF-8
#decodeURI() can throw URIError
en|decodeURIComponent(STR) #Same but also percent-encode characters that might have semantics in
#URIs parts:
# # : ? & = + $ ; , / @
#I.e. does not percent-encode the following (should escape if it has semantics
#for specific case):
# [:alnum:] - . _ ~ ! ' ( ) *
#Should be used for URI parts
[un]escape(STR) #Like en|decodeURIComponent() but using a different set of what's considered URI part:
# ~ ! ' ( ) # : ? & = $ ; ,
#I.e. does not percent-encode the following:
# [:alnum:] - . _ * + / @
#Also, uses UTF-16, with Unicode chars percent encoded as %uUUUU, not a series of %XX
#Deprecated
┌─────────────┐
│ UNICODE │
└─────────────┘
ENCODING ==> #UTF-16:
# - S_CODEPOINT: 1 character === 1 codepoint
# - CODEPOINT: 1 character === 1 codepoint (<U+10000) or 2 surrogate codepoints (>=U+10000)
# - isolated|inverted surrogate pairs are not invalid: they are considered their own character|codepoint instead
#Exceptions:
# - encode|decodeURI[Component]() uses UTF-8
# - the platform (Node.js, Web APIs) provides with encoding-specific operations. often with UTF-8
S_CODEPOINT #Single Unicode character STR. Any, even U+10FFFF
CODEPOINT #Like S_CODEPOINT except > U+FFFF treats each surrogate as own character.
#All STR operations use CODEPOINTs:
# - including STR.length, STR[NUM], STR.*(), comparison, max length
# - except:
# - STR iteration
# - STR.to[Locale]Lower|UpperCase(), STR.trim*()
# - \u{}, String.fromCodePoint(), STR.codePointAt(), /REGEXP/u
[S_]CODEPOINT[_NUM] #Same as NUM
\uCODEPOINT_HEXA #CODEPOINT in a STR
\u{S_CODEPOINT_HEXA} #S_CODEPOINT in a STR
String.fromCharCode
(CODEPOINT_NUM...)->STR #
String.fromCodePoint
(S_CODEPOINT_NUM...)->STR #Returns STR
STR.charCodeAt(NUM)->CODEPOINT #NUM is CODEPOINT-wise
#For > U+FFFF, if NUM is on:
# - the first|second surrogate pair: CODEPOINT is returned
#If NUM out-of-range, returns NaN.
STR.codePointAt(NUM)->S_CODEPOINT #NUM is CODEPOINT-wise
#For > U+FFFF, if NUM is on:
# - the first surrogate pair: S_CODEPOINT is returned
# - the second surrogate pair: CODEPOINT is returned
#If NUM out-of-range, returns undefined.
/REGEXP/u # - operate with S_CODEPOINT instead of CODEPOINT
# - for example for . [] {NUM,NUM2} etc.
# - stricter REGEXP syntax enforcement, e.g. /{/ throws
# - allow using \p or \P
STR.normalize([STR2]) #Some codepoint sequences are equivalent, e.g. with diacretics
#Equivalence types:
# - canonical: same abstract character, including visual appearance and behavior
# - example: '\u00e9' (é) (composed) and '\u0065\u0301' (e ́) (decomposed)
# - compatibility: looser superset, i.e. enough if can be treated alike
# - examples:
# - '\ufb00' (ff ) (composed) and '\u0066' (ff) (decomposed)
# - '\u24b9' (Ⓓ ) (composed) and '\u0044' (D) (decomposed)
#Can be:
# - "NFC" (def): decomposes then compose (canonical)
# - "NFD": decompose (canonical)
# - "NFKC": decompose then compose (compatibility)
# - "NFKD": decompose (compatibility)
STR.isWellFormed()->BOOL 20.0.0#False if contains isolated|inverted surrogate pairs
STR.toWellFormed()->STR 20.0.0#Replaces isolated|inverted surrogate pairs by U+FFFD
┌─────────────┐
│ SYMBOLS │
└─────────────┘
Symbol([STR]) #SYM
SYM.description #STR
SYM == != === !== SYM #Symbols are compared by identify, regardless of SYM.description
SYM.toString()->'Symbol(STR)' #STR is SYM.description
OBJ[SYM] #Same as OBJ["RANDOM"], semantically for private members.
#Different methods to enumerate (see above)
#SYM properties ignored by JSON.stringify()
Symbol.for(STR) #Like Symbol(STR), except "register" it to a global store using STR as a key,
#so that Symbol.for(STR) === Symbol.for(STR)
Symbol.keyFor(SYM) #Returns STR if SYM was created as Symbol.for(STR), undefined otherwise.
WELL-KNOWN SYMBOLS ==> #SYM that can be used to override native behavior.
#E.g. Symbol.iterator
#When printed, sometimes abbreviated to @@VAR
┌─────────────┐
│ OBJECTS │
└─────────────┘
[new] Object(VAL) #Used for implicit|explicit conversion.
#For any type:
# - new type is OBJ, i.e. different type
# - but behavior is same thanks to implicit transtyping
#For Number|BigInt|String|Boolean:
# - can also use new TYPE(VAL)
#For undefined|null:
# - prototype is null
# - no implicit transtyping
#All OBJs inherit from Object except Object.create(null)
OBJ.VAR #Access property (can be any type)
OBJ['VAR'] #OBJ.VAR has same naming restrictions as QUAL VAR, except can be a reserved word
#OBJ['VAR'] can use any valid STR
#Throws with undefined|null
OBJ?.VAR #Like OBJ == null ? undefined : OBJ.VAR
OBJ?.['VAR'] #Like OBJ == null ? undefined : OBJ['VAR']
{ VAR[: VAL] ... } #Literal OBJ.
#If could be interpreted as a { ... } structure (e.g. beginning of line),
#wrap with ()
#VAR can either:
# - be "VAR" or 'VAR': any valid STR
# - be unquoted, with same naming restrictions as QUAL VAR except:
# - can be reserved keywords
# - can be any NUM, which will be converted to STR
#Def VAL is VAR
#VAR can be [STR], for dynamic property name
#If duplicate key, the last one will overwrite the ones before.
{ FUNC() {...} ... } #Same as { FUNC: function FUNC() {...} ... }
PROPERTIES ORDER ==> #Guaranteed to be in that order:
# - 'NUM', sorted numerically
# - STR, sorted by creation time
# - SYM, sorted by creation time
OWN / ENUMERABLE ==> # +-------------------------------------------------------+-------------------------------+
# | Own | Own+inherited |
# +------------+-------------------------------------------------------+-------------------------------+
# | enum | OBJ.propertyIsEnumerable('VAR'|SYM)->BOOL | for (QUAL NOT_SYM_VAR in OBJ) |
# | | Object.keys(OBJ)->'VAR'_ARR | |
# | | Object.values|entries|fromEntries(...) | |
# | | Object.assign(...), { ...OBJ } | |
# +------------+-------------------------------------------------------+-------------------------------+
# | [non-]enum | OBJ.hasOwnProperty('VAR'|SYM)->BOOL | 'VAR'|SYM|#PROP in OBJ |
# | | Object.hasOwn(OBJ, 'VAR'|SYM)->BOOL | |
# | | Reflect.ownKeys(OBJ)=>'VAR'|SYM_ARR | |
# | | Object.getOwnPropertyNames(OBJ)->'VAR'_ARR | |
# | | Object.getOwnPropertySymbols(OBJ)->SYM_ARR | |
# | | Object.getOwnPropertyDescriptor(OBJ, 'VAR'|SYM)->OBJ2 | |
# | | Object.getOwnPropertyDescriptors(OBJ)->OBJ3 | |
# +------------+-------------------------------------------------------+-------------------------------+
'VAR'|SYM in OBJ #Returns true if OBJ['VAR'|SYM] is member
#Negation: !('VAR' in OBJ)
#PROP in OBJ #Same for private #PROP
OBJ.hasOwnProperty('VAR'|SYM)
->BOOL #Returns true if OBJ['VAR'|SYM] is own
Object.hasOwn(OBJ, 'VAR'|SYM)
->BOOL #Same
OBJ.propertyIsEnumerable
('VAR'|SYM)->BOOL #Returns true if OBJ['VAR'|SYM] is own + enumerable
Object.keys(OBJ)->'VAR'_ARR #Returns keys that are own + enumerable + not SYMs
Reflect.ownKeys(OBJ)
->'VAR'|SYM_ARR #Returns keys that are own
Object.getOwnPropertyNames(OBJ)
->'VAR'_ARR #Returns keys that are own + not SYMs
Object.getOwnPropertySymbols(OBJ)
->SYM_ARR #Returns keys that are own + SYMs
Object.values(OBJ) #Same as Object.keys() but for values
Object.entries(OBJ) #Same as Object.keys() but for [KEY, VALUE]
Object.fromEntries(ITERABLE) #Inverse Object.entries(), i.e. from ITERABLE of [KEY, VALUE] to OBJ
#As opposed to Object.entries(), KEY that SYM are not skipped
Object.assign(OBJ[, OBJ2...]) #Shallow copy of own enumerable OBJ2 members (including SYMs) to OBJ, which is returned.
#Properties copied in OBJ are:
# - always configurable|writable, even if OBJ2 members were not
# - resolved, if OBJ2 members were getters
{ [...] ...OBJ2 [...] } #Same as Object.assign({}, OBJ2, ...)
[QUAL] { [...] ...OBJ } = OBJ2 #Does Object.assign(OBJ, OBJ2), except the parts mentioned in ...
┌────────────────────────┐
│ OBJECT DESCRIPTORS │
└────────────────────────┘
{ get|set VAR(...) {...} } #Like { VAR(...) {...} } followed by Object.defineProperty() with configurable|enumerable true
Object.defineProperty #Assign OBJ['VAR'|SYM] = VAL, where VAL depends on OBJ2 ('descriptors'):
(OBJ, 'VAR'|SYM, OBJ2) # - either (def: value undefined):
# - value VAL
# - get and|or set:
# - get()->VAL
# - called at OBJ.VAR
# - def: returns undefined
# - set(VAL)
# - called at OBJ.VAR = VAL
# - `this` is OBJ
# - no return value, i.e. must be modified
# - must not set this.VAR to avoid infinite recursion
# - def: TypeError on set
# - enumerable BOOL (def: false):
# - if false, not listed by Object.keys|...(), OBJ.propertyIsEnumerable() and for (QUAL STR in OBJ)
# - writable BOOL (def: false):
# - if false, throws TypeError if OBJ.VAR = VAL
# - even if VAL did not change
# - even if VAR is inherited through the __proto__ chain
# - but can still Object.defineProperty() if configurable
# - not possible with get|set():
# - always undefined
# - setting it throws
# - configurable BOOL (def: false):
# - if false, throws TypeError:
# - if:
# - delete OBJ.VAR
# - set configurable|writable false -> true
# - set enumerable|get|set -> !== value
# - go from get|set <-> value
# - not if:
# - set value, or OBJ.VAR = VAL
# - except if current writable false
# - set writable true -> false
# - VAR is inherited through the __proto__ chain
#If own property already exists, default values are current descriptors instead.
Object.getOwnPropertyDescriptor #Returns OBJ.VAR descriptor OBJ2
(OBJ, 'VAR'|SYM)->OBJ2 #Even if not declared through Object.defineProperty()
#Returns undefined if does not exists or is not own.
#Including SYMs
Object.defineProperties(OBJ, OBJ3)
Object.getOwnPropertyDescriptors
(OBJ)->OBJ3 #Same but using OBJ3 { 'VAR': OBJ2 ... } instead.
Object.preventExtensions(OBJ) #Make OBJ non-extensible, i.e. TypeError if:
# - adding new property
# - setting __proto__
#Not recursive.
Object.isExtensible(OBJ) #
Object.seal(OBJ) #Make OBJ non-extensible, non-configurable
#Not recursive.
Object.isSealed(OBJ) #
Object.freeze(OBJ) #Make OBJ non-extensible, non-configurable, non-writable (except get|set())
#Not recursive.
Object.isFrozen(OBJ) #
┌────────────────┐
│ PROTOTYPES │
└────────────────┘
OBJ.__proto__ #When OBJ.VAR is not defined, OBJ.__proto__.VAR is tried
# - recursively (prototype chain)
# - the last __proto__ is null
#Setting OBJ.__proto__[...].VAR creates OBJ.VAR instead
# - including with Object.defineProperty() and delete
# - even if value did not change
#I.e. inheritance is prototype-based.
#__proto__ itself is considered an inherited, non-enumerable, writable, configurable property
Object.getPrototypeOf(OBJ)->VAL #Same but less standard and:
# - returns `null` instead of `undefined` for null prototype
# - does not return `undefined` if no prototype in the chain is Object.prototype
#Like OBJ.__proto__, throws if OBJ is undefined|null
Object.setPrototypeOf
(OBJ, VAL)->OBJ #Same as OBJ.__proto__ = VAL (to avoid because performance issues)
OBJ.isPrototypeOf(OBJ2) #Returns true if OBJ2.__proto__[...] === OBJ
#I.e. if isPrototypeOf TYPE, also true for TYPE_PARENT
#Always false for non-OBJs, but does not throw.
super.* #Same as this.__proto__.*
super[EXPR] #Can be used in any OBJ method using shortcut notation
MULTIPLE INHERITANCE ==> #Not supported, but be approximated using composition|mixins, including:
# - own members: call several TYPE_PARENT(...) in constructor
# - inherited members: merge TYPE_PARENT.prototype to TYPE.prototype
# - con: copied, not referenced (except deep properties)
┌──────────────────┐
│ CONSTRUCTORS │
└──────────────────┘
TYPE #Constructor FUNC
#Cannot be an arrow FUNC
#By convention TYPE starts with uppercase
TYPE.prototype #Properties that all TYPE instances should inherit
#Set to empty OBJ when any FUNC is instantiated
# - not set for arrow nor bound FUNCs
Object.create #Returns { __proto__: TYPE.prototype }
(TYPE.prototype[, OBJ])->OBJ2 #Then calls Object.defineProperties(OBJ2, OBJ)
Object.create(null) #OBJ where __proto__ is null instead of Object.prototype
PROTOTYPE POLLUTION ==> #Setting core OBJ.* property to override core behavior.
#For: OBJ.hasOwnProperty|propertyIsEnumerable|isPrototypeOf|to[Locale]String|valueOf()
#Can be prevented with:
# - call-time: Object.prototype.FUNC.call(OBJ, ...) instead of OBJ.FUNC(...)
# - declaration-time: Object.create(null)
OBJ instanceof TYPE #Returns true if OBJ.__proto__[...] === TYPE.prototype
#If TYPE is bound, unbound it first.
OBJ[Symbol.hasInstance](VAR)
->BOOL #Define to override VAR instanceof OBJ
REALMS ==> #TYPEs might be coming from another environment with a different global scope
# - e.g. when using Node.js 'vm', or iframes in browser
#This makes TYPE check fail (including instanceof)
# - except for native types, including undefined|null and Symbol.for()
#But typeof and Object.prototype.toString.call() work
TYPE.prototype.constructor #TYPE itself.
#Set when any non-arrow|bound FUNC is instantiated
#Meant for type checking on instances.
#Not used by new TYPE
TYPE.* #Static members, i.e. properties of TYPE, not instances
#Can be inherited by using TYPE.__proto__ = TYPE_PARENT
EXAMPLE ==> # function TYPE(...) {
# TYPE_PARENT.apply(this[, ...])
# this.VAR = ...; ...
# }
# TYPE.prototype = Object.create(TYPE_PARENT.prototype)
# TYPE.prototype.constructor = TYPE
# TYPE.__proto__ = TYPE_PARENT
new TYPE[(...)] #Create OBJ with Object.create(TYPE.prototype)
# - if TYPE is bound, unbound it first.
#Then call TYPE.call(OBJ, ...)