-
Notifications
You must be signed in to change notification settings - Fork 0
/
JavaScript.txt
1064 lines (403 loc) · 16.3 KB
/
JavaScript.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
DATA TYPES:
Numbers:
0-9
Infinity, -Infinity
NaN
NaN will propagate through an expression, and will return itself
as opposed to an error.
STRINGS:
Must be inside of quotes.
"" & '' both serve identically.
STRING LITERALS
`` (backticks) can be used to embed something else, such that
`Two plus two equals ${2 + 2}`;
A string may be a single character eg. (c)
If an error such as
unterminated string literal
Go back through and make sure all strings are contained within quotation marks.
The Same type of quotation marks that were used to open the string cannot be contained
within the string itself.
eg
var bigmouth = 'I've got no right to take my place...';
This will retrun an error.
This can be overcome by "escaping" the character with a backslash \
var bigmouth = 'I\'ve got no right to take my place...';
bigmouth; "I've got no right to take my place..."
The Number object can be used to convert a string to a number.
var myString = '123';
var myNum = Number(myString);
typeof myNum;
toString() will convert a number to a string:
var myNum = 123;
var myString = myNum.toString();
typeof myString;
STRINGS:
METHODS AND PROPERTIES
LENGTH
String Length:
The Length Property returns the length of a string:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
INDEXOF
Finding a String in a String:
The indexOf() returns the index of (the position of) the first occurance of a specified text
in a string.
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); \\ 7
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
This is similar to search()
The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).
EXTRACTING
3 Ways
slice(start, end)
substring(start, end)
substr(start, length)
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
ar res = str.slice(7, 13); \\ Banana
If the numbers in slice() are negative, it will count from the end of the string.
substring() is the same, but it can't accept negative numbers.
substr() is similar to slice(), but the second numbe specifies the length
what will be cut out after the starting point of the first number
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6); \\ Banana
REPLACE
replace() replaces a value in a string with something else.
This does not change the orignal string, but returns a new one.
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
To replace case insensitive, use a regular expression with an /i flag (insensitive):
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
To replace all instances globally within a string, use a /g flag
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");
To Replace All instances within a string - supported by all modern browsers 2022
String.prototype.replaceAll()
REPEAT
'lol'.repeat(5);
'lollollollollol'
CONVERT TO UPPERCASE
or lowercase
toUpperCase()
toLowerCase()
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
CONCATENATION METHOD
concat() this joins two or more strings
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2); // Hello World
This can be used instead of the + operator
This would return the same thing as the above
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");
REMOVING WHITE SPACE
String.trim() trims off excess white space at the start and end of a string
EXTRACTING STRING CHARACTERS
charAt(position)
var str = "HELLO WORLD";
str.charAt(0); // returns H
charCodeAt(position)
Returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
Property access []
var str = "HELLO WORLD";
str[0]; // returns H
CONVERTING A STRING
TO AN ARRAY
split()
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is ommitted, it will return the whole string as an array in index[0].
If the separator is "" the returned array will be an array of single characters.
BOOLEAN:
True or False
let nameFieldChecked = true; // yes, name field is checked
let ageFieldChecked = false; // no, age field is not checked
Booleans also come as the result of comparisons, eg:
let isGreater = 4 > 1;
alert( isGreater ); // true (the comparison result is "yes")
NULL:
Empty. Nothing. Refers to Nothing Else. It's just an empty nothing.
It has to be assigned
Explicitly defines something as having no value. Useful for when you want to make it clear in the code that there is no data here.
let age = null;
The value of age is unknown
UNDEFINED:
A value is not assigned
Variables that do not have an assigned value are undefined.
If a variable is declared but not assigned a value,
the value is undefined
let x;
alert(x); // shows "undefined"
Technically, you can do
let x = 123;
x = undefined;
alert(x); // "undefined"
It is advisable to not do this, and to instead assign a value of "null"
to variables that don't have a value.
Undefined can be used as a check to see if a variable has a value.
OBJECTS & SYMBOLS
object is a non-primitave data type used to store lareger collections of data.
The symbol type is used to create unique lables for objects.
TYPEOF
The typeof operator returns the type of the argument.
It's useful for processing values of different types differently,
or for a quick check of what datatype a variable is.
Two forms of Syntax:
As an operator: typeof x
Function style: typeof(x)
These both work exactly the same
Examples:
typeof undefined // "undefined"
typeof 0 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof Symbol("id") // "symbol"
typeof Math // "object" (1)
typeof null // "object" (2)
typeof alert // "function" (3)
CONDITIONALS:
COMPARISONS
A comparison: < > >= <= == returns a boolean (true, false)
This can be assigned to a variable:
let result = 5>4; // true
Strings can be compared just as well as numbers
alert( 'Z' > 'A' ); // true
alert( 'Glow' > 'Glee' ); // true
alert( 'Bee' > 'Be' ); // true
1. Compare first characters of both strings.
2. If the first one is greater(or less), then the first string is greater(or less) than the second. We’re done.
3. Otherwise if first characters are equal, compare the second characters the same way.
4. Repeat until the end of any string.
5. If both strings ended simultaneously, then they are equal. Otherwise the longer string is greater.
Lowercase letters have a higher value than uppercase. Think of the order
Words would be in in a dictionary.
When variables of different types are compared, they are converted to numbers.
alert( '2' > 1 ); // true, string '2' becomes a number 2
alert( '01' == 1 ); // true, string '01' becomes a number 1
For Booleans:
true == 1
false == 0
It is possible that at the same time:
Two values are equal.
One of them is true as a boolean and the other one is false as a boolean.
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true
alert(a == b); // true!
STRICT EQUALITY
===
Strict Equality: There is no type conversion with this.
0 == false
"" == false
This is because operands of different types are converted to numbers
through the equality operator ==
alert(0 === false); // false, because 0 and false are of different types.
!== Strict non equality operator
COMPARISON WITH NULL
& UNDEFINED
alert( null === undefined ); // false
Null == undefined (This is the only case in which they are equilivent)
These two equal each other in terms of ==
But not in any other case.
< > <= >=
In this case, null (0) and undefined (NaN) are converted to numbers.
alert( null > 0 ); // (1) false
alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true
Since comparisons convert null to 0, null > 0 is false
In an equality check, == , null is a special value different from 0
So null == 0 is false.
In comparison >= , null is converted to 0, so null >= 0 is true.
alert( undefined > 0 ); // false (1)
alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)
Undefined can only pass an equality test, == , with Null, nothing else.
To avoid problems, try no never include null/undefined in comparisons.
Making a separate check for null/undefined is a good idea.
LOGICAL OPERATORS:
|| (or) && (and) ! (not)
|| (OR)
|| can be applied to any value, not just booleans.
result = a||b;
With booleans, there are four possible outcomes
alert( true || true ); // true
alert( true || false ); // true
alert( false || true ): // true
alert(false || false); // false
If an operand is not boolean, then it’s converted to boolean for the evaluation.
For instance, a number 1 is treated as true, a number 0 – as false:
Often, || is used as part of an if statement to see if any of the given conditions are correct.
let hour = 9;
if (hour < 10 || hour > 18) {
alert( 'The office is closed.' );
}
This can be applied with more than two values:
let hour = 12;
let isWeekend = true;
if (hour < 10 || hour > 18 || isWeekend) {
alert( 'The office is closed.' ); // it is the weekend
}
The || operator does the following:
1. Evaluates operands from left to right
2. For each operant, convert it to a boolean. If the result is true then stop and return the original
value of that operand
3. If all other operands were false, returns the last operand.
alert( 1 || 0 ); // 1 (1 is truthy)
alert( true || "no matter what" ); // true is truthy
alert ( null || 1 ); // 1 (1 is the first truthy value)
alert ( null || 0 || 1 ) // 1 (the first truthy value)
alert ( null || undefined || 0 ); // 0 (all falsy, last value returned)
eg:
let currentUser = null;
let defaultUser = "John";
let name = currentUser || defaultUser || "unnamed"
alert( name ); // selects "John" (The first truthy value).
Operands can be both values and random expressions:
let x;
true || (x = 1);
alert( x ); // undefined ((x = 1) was was not evaluated)
...therefore
let x;
false || (x = 1);
alert(x); // 1
&& (AND)
result = a && b;
alert( true && true); // true
alert( true && false); // false
alert( false && true); // false
alert( false && false); // false
let hour = 12;
let minute = 30;
if (hour == 12 && minute == 30) {
alert( 'Time is 12:30' );
}
if (1 && 0) { //evaluate as true and false
alert( 'Won't work because the result is falsy)
}
AND seeks the first falsy value.
result = value1 && value2 && value3;
&& evaluates as such:
1. Evaluates from Left to Right
2. Finds the first falsy value, and returns it.
3. If all are truthy, returns the last value if no falsy were found.
// if the first operand is truthy,
// AND returns the second operand:
alert( 1 && 0 ); // 0
alert( 1 && 5 ); // 5
// if the first operand is falsy,
// AND returns it. The second operand is ignored
alert( null && 5 ); // null
alert( 0 && "no matter what" ); // 0
&& Has a higher precedence than ||
! (NOT)
result = !value;
1. Converts the operator to a boolean type (true/false)
2. Returns an inverse value.
alert( !true ); // false
alert (!0 ); // True
A double NOT !! is sometimes used to convert a value to a boolean type:
alert( !!"non-empty string" ); // true
alert( !!null ); // false
This would be the same as doing:
alert( Boolean("non-empty string") ); //true
alert( Boolean(null) ); // false
! (NOT) has a higher precedence than || , &&
Math.object
An object built into the JS language that provides a useful set of generalized mathematical stuff. Like rounding, and tangents, and Random, and PI, etc, etc, etc, etc
Math.PI
IF:
if (condition) {
block of code to be executed if the condition is true
}
ELSE
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
ELSE IF
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
NESTING
if (condition) {
if (condition2) {
code to be run
}
else if (condition3) {
code to be run
}
}
if (choice === 'sunny') {
if (temperature < 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
} else if (temperature >= 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
}
}
Logical Operators && and || can be used to condense this:
&&: All conditions must return true.
||: At least one condition must return true.
&& Example:
if (choice === 'sunny' && temperature < 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
} else if (choice === 'sunny' && temperature >= 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some suncream on.';
}
|| Example:
if (iceCreamVanOutside || houseStatus === 'on fire') {
console.log('You should leave the house quickly.');
} else {
console.log('Probably should just stay in then.');
}
! Can be used to negate an expression.
SWITCH:
These are similar to the if..else statements.
They search throught a number of specific cases given, and only
run the code that is presented under the case that returns true.
switch (expression) {
case choice1:
run this code;
break;
case choice2:
run this code instead;
break;
// include as many cases as you like
default:
actually, just run this code;
}
1. The Keyword switch
2. (expression or value) inside parenthesis {
3. Keyword case followed by a choice that the expression/value could be.
4. Some code to run if the choice matches the expression.
5. break statement followed by semicolon;
If the case matches the expression/value, the code is run and the browser stops
executing the code here.
...as many of these as you need until...
6. Keyword default:
run this code;
This is the default option that runs if none of the cases match the value/expression.
}
The Default value can be omitted if it is impossible that none of the cases are met.
TERNARY OPERATOR:
( condition ) ? run this code : run this code instead