-
Notifications
You must be signed in to change notification settings - Fork 2
/
JS.js
3023 lines (2169 loc) · 81.3 KB
/
JS.js
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 - Page Behavior - by Beumsk
// To create a comment. Shown in code only. Indent 2spaces
/* Multiple line comment */
// TODO: --> best practice to indicate things to do in the code
// FIXME: --> best practice to indicate things to fix in the code
// MAIN JS - main syntax
// Variable
var a = "example";
console.log(a); // example
// Function; also var example = function() {};
function example(num) { // num is the function parameter
// code block;
console.log(num * num);
}
example(5); // run the function -> 25 (5 is the function argument)
// Double arg Function (also called currying)
function say(arg1) {
return function(arg2) {
return arg1 + " " + arg2;
}
}
say("hello")("world"); // hello world
// Infinite currying
function add(a) {
return function(b) {
if (b) return add(a+b);
return a;
}
}
console.log(add(2)(3)(4)(8)()); // 2+3+4+8=17
// IIFE (Immediately Invoked Function Expression) -> doesn't need to be called to run
(function example(text) {
console.log(text);
})("hellow world");
// Callback function
function greeting(name) {
console.log('Hello ' + name);
}
function processGreeting(name, callback) {
callback(name);
}
processGreeting('you', greeting); // Hello you
// Array (careful!-> if variable is set equal to another array, they will be linked and influence each other)
var numbers = [one, two, three];
console.log(numbers[0]); // 'one'
console.log(numbers[0], numbers[1]); // 'one two'
// Object
var dog = {
name: "Rex",
race: "Pitbul",
age: "6"
};
console.log(dog.name); // Rex
console.log(dog["name"]); // Rex
// Condition
if (a === 1) {
// code block;
} else if (a === 2) {
// code block;
} else {
// code block;
}
// Ternary operator
var a = (b > 10) ? "Over ten" : "Under ten"; // if b > 10, a value will become "Over ten"; otherwise, "Under ten"
// Short circuiting
var a = true && true; // returns true
var a = true && false; // returns false
var a = false || false; // returns false
var a = true || false; // returns true
// Switch condition
switch (a) {
case 1:
// code block;
break;
case 2:
case 3:
// code block;
break;
default:
// code block;
}
// While loop
while (a == 1) {
// code block;
}
// Do while loop; Will execute code block at least once
do {
// code block;
} while (false);
// For loop
for (i = 0; i < a.length; i++) {
// code block;
}
// ForEach loop from an array
a.forEach(function(item) {
// code block;
});
// DOM syntax
document.getElementsByTagNamegName("tag"); // will return tag elements as an array
document.getElementsByClassName("class"); // will return .class elements as an array
document.getElementById("id"); // will return #id element
document.querySelector("tag"); // will return first tag of document; selection similar to css (or jquery)
document.querySelectorAll("tag"); // will return all tags as an array; Note that it isn't updated live as other selectors are
document.getElementById("id").setAttribute("src", "www.site.com"); // set/change attribute; can often be written something.src("change");
document.getElementById("id").innerHTML = "some text"; // change #id content
document.getElementById("id").textContent = "some text"; // similar to innerHTML without tag understanding; can use += to add some text
document.getElementById("id").style.backgroundColor = "red"; // change style of background-color; everything is camelCased
document.getElementById("id").classList.add("class"); // add a class
var newDiv = document.createElement("div"); newDiv.innerHTML = "text"; document.body.appendChild(newDiv); // create div, add content and append to body
document.body.removeChild(newDiv); // remove newDiv
document.replaceChild(newDiv, otherDiv); // replace newDiv wth otherDiv
newDiv.addEventListener("click", function () {/*code block;*/}); // new event click
newDiv.removeEventListener("click", namedFunction); // remove event click
newDiv.addEventListener("click", function once() {this.removeEventListener("click", once)}); // event click only once
setTimeout(function (){/*code block;*/}, 1000); // run code after 1sec
var timeout = setTimeout(func, 1000); clearTimeout(timeout); // timeout is set and then cleared
setInterval(function (){/*code block;*/}, 1000); // run code every 1sec
var interval = setInterval(func, 1000); clearInterval(interval); // interval is set and then cleared
document.querySelector("form").addEventListener("submit", function (e) {e.PreventDefault();}); // prevent default (submit and refresh)
document.querySelector(".item").addEventListener("click", someFunc); function someFunc(e) {e.target.style.color = "red"} // targets clicked element
JSON.stringify(objectJS); // JS objects array into JSON string
JSON.parse(stringJSON); // JSON string into JS objects array
// CONSOLELOG
// show something in js console
console.log("Text"); // Text
console.log("up \n down"); // \n acts like enter
console.log("\' \" \\ "); // to use those tricky characters
console.log(3 + 4 - 1 * 4 / 2); // process and give answer
console.log(10 % 3); // show the rest of division -> it is called modulo
console.log("hel" + "lo"); // show addition of the two strings "bonjour"
console.log("hello", "you"); // show both strings with a space between "hello you"
console.log(isNaN(10)); // returns false (true if it is actually NotaNumber)
console.log(typeof "string"); // can return number, boolean, string, function, object (array return object in JS)
console.warn("Warning"); // display some content as a warning message
console.assert(2 == 2); // returns undefined if true and returns detailed error when false
console.table(["apples", "oranges", "bananas"]); // returns a nice table with index and values; works with objects as well !!IE
console.count(); // returns the number of time this particular call to count() has been called
console.trace(); // returns a stack trace to the console
console.log("%cStyled!", "font-weight: 800; color: red; font-size: 3rem;"); // style your log with some CSS
// ERRORS
// error example -> ReferenceError: not defined; ends the work of JS (the code afterwards will never be processed)
// STRICT MODE
// the strict mode changes bad syntax into actual errors; helping writing secure JS
// usage of strict mode; must be placed on top of code (or function)
"use strict";
x = 3; // not allowed; you must declare every variables
// TYPES
// Check types of elements;
// Typeof the main type checker
typeof 27; // number
typeof 27_000; // number; using numeric separator for big figures
typeof NaN; // number; weird i know
typeof "Hello"; // string
typeof (typeof 1); // string; typeof always returns a string
typeof true; // boolean
typeof Symbol(); // symbol
typeof undefined; // undefined
typeof what; // undefined
typeof {a:1}; // object
typeof [1, 2, 3]; // object
Array.isArray(arrayName); // true if an array
typeof function(){}; // function
typeof class C {}; // function
typeof Math.PI; // function
typeof null; // object
// Type conversion
String(true); // turns a value into a string --> "true"
100 + ""; // turns a value into a string --> "100"
Number("123"); // turns a value into a number --> 123
+null; // turns a value into a number --> 0
Number("hello"); // if the type isn't convertible --> NaN
Boolean(1); // turns a value into a boolean --> true
!!0; // turns a value into a boolean --> false
// VARIABLES
// JavaScript variables are containers for storing data values.
var a; // creates variable without value
var a; a = 10; // create variable with value of '10'
var a = 10; // shortened method
var a = 0; a += 1; a++; // add 1 and 1 to 'a' variable to reach 2
var a = 5; a -= 1; a--; // subtracts 1 and 1 to reach 3
var a = 5; a *= 5; a /= 5; // multiply by 5 and divide by 5 to reach 5
var a = 3; var b = a + 2; // 'b' will value 5 (3+2)
var a = 2 ** 3; // a = 2^3 = 8 !!IE
var a = 1e6; // 1000000
var a = 3; a = (a++, a*=3, a-=3); // serie of expression in one line --> a = 9
var a = "five" * 2; // 'a' is NaN; Not a Number
var a = (b > 10) ? "Over ten" : "Under ten"; // if b>10, a will equal "Over ten"; otherwise, "Under ten"; it's called ternary operator
var a = b > 0 ? "positive" : b < 0 ? "negative" : "zero"; // a will be positive, negative or zero according to b value
var a = true && false; // false; returns the first falsy value; default is last value
var a = true || false; // true; returns the first truthy value; default is last value
// ECMASCRIPT 6 !!IE
// VARIABLES
// Javascript const are containers you can only read; best use for value that will not change
// basic const
const a = 23;
// exception to rewrite const -> in a block
if (a === 23) {
const a = 7; // here and only here a = 7
}
console.log(a); // 23 again
// with arrays
const myArray = [1, 2, 3];
myArray[0] = 4; // can be freezed with Object.freeze()
// with objects
const myObject = {"key": "value"};
myObject.key = "otherValue"; // keys are not protected; can be with Object.freeze()
// with arrays
const myArray = [];
myArray = [8]; // not possible
myArray.push(8); // possible
// let are block-scoped variables
// let vs var
var a = 5, b = 10;
if (a === 5) {
let a = 4; // only 4 in if block
var b = 1;
console.log(a, b); // 4 1
}
console.log(a, b); // 5 1
// const are block-scoped variables that can't be reassigned but that can be updated
const arr = [1, 2, 3];
// Trying to reassign a const will give an error
arr = [5]; // ERROR
// Updating a const will succeed
arr.push(4); // [1, 2, 3, 4]
// Template literals
const easyText = `<p class="danger">
It's way easier to write strings with "quotes" and breaks
</p>`;
// FUNCTIONS
// arrow function
const myFunc = () => {
const myVar = "value";
return myVar;
}
// arrow function shorter
const myFunc = () => "value";
myFunc(); // "value"
// arrow function with parameter
const myFunc = (item) => item * 2;
myFunc(3); // 6
// arrow function with parameters
const myConcat = (arr1, arr2) => arr1.concat(arr2);
myConcat([1,2], [3,4]); // [1,2,3,4]
// arrow function with higher order functions (.map)
const arr = [1, 2, 3];
const squares = arr.map(x => x * x); // 1, 4, 9
// default parameter for function
function greet(name = "Anonymous") {
console.log("Hello" + name);
}
great(); // Hello Anonymous
great("Einstein"); // Hello Einstein
// Rest in function
function howMany(...args) {
return args.length + " arguments";
}
howMany("hi", 1, true); // 3 arguments
// ARRAYS
// Spread operator with array
const arr = [1, 9, 3, 4];
const arr2 = [17];
const newArr = [...arr, ...arr2, 21]; // [1, 9, 3, 4, 17, 21]
// Copy an array with spread
const arr = [1, 2, 3, 4];
const arrCopy = [...arr];
// String to array with spread
const str = "Aloha";
const arr = [...str]; // [A, l, o, h, a]
// rest for destructuring array
const [first, ...rest] = [1, 9, 3, 4]; // 1 and [9, 3, 4]
// some loop
const arr = [1, 2, 3, 4, 5];
arr.some((value) => { return (value == 3); }); // returns true; a single array value must be true to have a true output from an every loop
// every loop
const arr = [1, 2, 3, 4, 5];
arr.every((value) => { return (value == 3); }); // returns false; all array values must be true to have a true output from an every loop
// OBJECTS
// Object enumerables
const obj = {id: 1, name: "John"};
const entries = Object.entries(obj); // [['id', 1], ['name', 'John']]
const keys = Object.keys(obj); // ['id', 'name']
const values = Object.values(obj); // [1, 'John']
const objFromEntries = Object.fromEntries(entries); // {id: 1, name: "John"}
// spread with object
const obj = {id: 1, name: "John"};
const obj2 = {age: 29};
const newArr = {...obj, ...obj2, city: "Gotham"}; // {id: 1, name: "John", age: 29, city: "Gotham"}
// nested object update with spread
const user = {id: 3, name: 'Ron', organization: {name: 'Parks & Recreation', city: 'Pawnee'}};
const updatedUser = {...user, organization: {...user.organization, position: 'Director'}}; // {id: 3, name: "Ron", organization: {name: "Parks & Recreation", city: "Pawnee", position: "Director"}}
// Copy an object with spread
const obj = {id: 1, name: "John"};
const objCopy = [...obj]; // {id: 1, name: "John"}
// rest for destructuring object
const {id, ...rest} = {id: 1, name: "John", age: 29}; // 1 and {name: "John", age: 29}
// dynamic property name
const anything = 'something';
const short = 1;
const obj = {
[anything]: 5,
short
}
console.log(obj.anything, obj.something); // undefined, 5
console.log(obj.short); // 1
// Class syntax; replaces constructor function
class SpaceShuttle {
constructor(targetPlanet){
this.targetPlanet = targetPlanet;
}
}
const zeus = new SpaceShuttle('Jupiter');
// Getters and Setters
class Thermostat {
constructor(farenheit) {
this.farenheit = farenheit;
}
get temperature() {
return (this.farenheit - 32) * 5/9;
}
set temperature(celsius){
this.farenheit = celsius * 9.0 / 5 + 32;
}
}
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 °C
// DEEP COPY
// opposed to shallow copy, deep copy doesn't hold reference, even for nested objects and arrays
const obj1 = { id: 1, name: "one", user: { id: 1, name: "user1", start: new Date() } };
const deep1 = { ...obj1, user: { ...obj1.user } }; // fast but verbose
const deep2 = JSON.parse(JSON.stringify(obj1)); // slower (switch dates to string!)
const deep3 = structuredClone(obj1); // slowest
// POP-UPS
// launch pop-up
confirm("Are you sure to leave?"); // launch pop-up to confirm -> return true/false
prompt("Enter tour name"); // launch pop-up where user can answer -> return the answer
alert("hello"); // launch pop-up with text
var name = prompt("Enter your name :"); alert("hello, " + name); // pop-up to type name and another one to say 'hello name'
// USEFUL TOOLS
// other useful snippet of codes
// create audio and start it
var audio = new Audio("file.mp3");
audio.play();
// COMPARISONS
// Comparison and Logical operators are used to test for true or false
// smaller than
console.log(8 < 10); // true
console.log(10 < 8); // false
// greater than
console.log(10 > 8); // true
console.log(8 > 10); // false
// smaller or equal to
console.log(10 <= 10); // true
console.log(10 <= 8); // false
// greater or equal to
console.log(10 >= 10); // true
console.log(8 >= 10); // false
// equal to (weak)
console.log(10 == 10); // true
console.log(8 == 10); // false
// different from (weak)
console.log(10 != 8); // true
console.log(8 != 8); // false
// equal to and same type (strict)
console.log(10 === 10); // true
console.log(8 === 10); // false
// different and different type from (strict)
console.log(10 !== 8); // true
console.log(8 !== 8); // false
// 'AND'
console.log((10 > 8) && (10 === 10)); // true
console.log((10 > 8) && (8 === 10)); // false
// 'OR'
console.log((8 < 10) || (8 > 10)); // true
console.log((10 < 8) || (8 > 10)); // false
// opposite of instruction
console.log(!(10 < 8)); // true
console.log(!(8 < 10)); // false
// CONDITIONS
// Conditional statements are used to perform different actions based on different conditions
// return the sentence because it is true
var a = 4;
if (a === 4) {
console.log("a is 4"); // OK
}
// return the else if because if is false
var a = 4;
if (a > 4) {
console.log("a is greater than 4");
} else if (a === 4) {
console.log ("a is 4"); // OK
}
// return the else because it's false
var a = 4;
if (a > 4) {
console.log("a is greater than 4");
} else if (a < 4) {
console.log("a is less than 4");
} else {
console.log ("a isn't greater or less than 4 --> a is 4"); // OK
}
// switch is a better way for defined options // do not forget the break; !
var a = 4;
switch (a) {
case "1":
console.log("a is 1");
break;
case "2":
console.log("a is 2");
break;
case "4":
console.log("a is 4"); // OK
break;
default: // if none of cases is true
console.log("a is a variable");
break;
}
// if you do not use breaks, cases will merge till the next break
var a = 4;
switch (a) {
case 1:
case 2:
case 3:
console.log("a is 1, 2, 3");
break;
case 4:
console.log("a is 4"); // OK
break;
case 7:
case 8:
case 9:
console.log("a is 7, 8, 9");
break;
}
// SHORT CIRCUIT
// handy way to manage short conditions
// Logical &&
var a = true && true; // true
var a = true && false; // false
var a = false && false; // false
var a = "cat" && "dog"; // "dog"
// Logical ||
var a = true || true; // true
var a = true || false; // true
var a = false || false; // false
var a = "cat" || "dog"; // "cat"
// with a function
function short(test) {
var a = test || "Test is not defined"; // a = test value if defined; otherwise a = string
}
// chose between functions
function short() {
func1() || func2(); // runs func1 if it exists; otherwise runs func2
}
// LOOPS
// while the condition is true, the code is looping
// while loop; use it by default
var a = 1;
while (a <= 4) {
console.log(a);
a++;
} // 1 2 3 4
// /!\ careful with infinite loops --> it breaks applications
var a = 1;
while (a <= 4) {
console.log(a); // the condition will always be true and will therefore lead to infinite loop
}
// do while loop; while alike, but will do the first block code at least once (even if while is false)
var a = 1;
do {
console.log(a);
a++;
}
while (a < 1); // 1
// for loop; use when you know the number of loops
var a;
for (a = 1; a <= 4; a++) {
console.log(a);
} // 1 2 3 4
// when variable is only used in the for loop
for (var a = 1; a <= 4; a++) {
console.log(a);
} // 1 2 3 4
// break; end of the loop
for (var a = 1; a <= 4; a++) {
if (a === 3) {
break;
}
console.log(a);
} // 1 2; stops when 3 reached
// continue; breaks one iteration in the loop
for (var a = 1; a <= 4; a++) {
if (a === 3) {
continue;
}
console.log(a);
} // 1 2 4; skips 3
// fizzbuzz (similar to dingdingbottle)
for (var a = 1; a <= 100; a++) {
if ((a % 3 === 0) && (a % 5 === 0)) {
console.log("FizzBuzz");
} else if (a % 3 === 0) {
console.log("Fizz");
} else if (a % 5 === 0) {
console.log("Buzz");
} else {
console.log(a);
}
} // 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
// forEach loop
var a = [1, 2, 3, 4, 5];
a.forEach(function(element) {
console.log(element);
}); // 1 2 3 4 5
// recursion
function countDownFrom(number) {
if (number === 0) { return; }
console.log(number);
countDownFrom(number - 1);
}
countDownFrom(5); // 5 4 3 2 1
// FUNCTIONS
// A JavaScript function is a block of code designed to perform a particular task. You need to invoke it
// simple function
function sayHello() {
console.log('Hello !');
}
sayHello(); // Hello !
// function with return; function exits at return statement, whatever comes after a return line never outputs
function sayHello() {
return 'Hello !';
}
console.log(sayHello()); // Hello !
// function with return and variable
function sayHello() {
return 'Hello !';
}
var resultat = sayHello();
console.log(resultat); // Hello !
// local variables; they can't be used outside the function
function sayHello() {
var message = 'Hello !';
return message;
}
console.log(sayHello()); // Hello !
console.log(message); // error, variable works only inside function
// function with parameters
function sayHello(name) {
var message = 'Hello, ' + name + ' !';
return message;
}
console.log(sayHello('Beumsk')); // Hello, Beumsk !
// function with multiple parameters
function sayHello(name, surname) {
var message = 'Hello, ' + name + ' ' + surname + ' !';
return message;
}
console.log(sayHello('Mr', 'Beumsk')); // Hello, Mr Beumsk !
// function with for loop
function carre(number) {
var resultat = number * number;
return resultat;
}
for (var i = 0; i <= 10; i++) {
console.log(carre(i));
}
// function with if
function min(number1, number2) {
if (number1 > number2) {
return number2;
} else {
return number1;
}
}
console.log(min(9, 1));
// function nested in function
function first() {
console.log("first");
return function() {
console.log("second");
}
}
first(); // logs first
first()(); // logs first and second
// Double arg Function
function say(arg1) {
return function(arg2) {
return arg1 + " " + arg2;
}
}
say ("hello")("world"); // hello world
// calculator
function calculator(number1, mult, number2) {
if (mult === '+') {
return number1 + number2;
} else if (mult === '-') {
return number1 - number2;
} else if (mult === '*') {
return number1 * number2;
} else if (mult === '/') {
return number1 / number2;
}
}
console.log(calculator(4, "+", 6)); // returns 10
console.log(calculator(4, "-", 6)); // returns -2
console.log(calculator(2, "*", 0)); // returns 0
console.log(calculator(2, "/", 0)); // returns Infinity
// circle perimeter and radius
function perimeter(radius) {
return 2 * Math.PI * radius;
}
function area(radius) {
return Math.PI * radius * radius;
}
console.log(perimeter(10)); // 62.83185307179586
console.log(area(10)); // 314.1592653589793
// STRING
// methods working on text strings
// string.length with variables
var str = "Kangaroo";
console.log(str.length); // 8
// string.includes() check if string includes another stinrg
var str = "Kangaroo";
console.log(str.includes("anga")); // true
// string.startsWith() check if string starts with something
var str = "Kangaroo";
console.log(str.startsWith("Kan")); // true
// string.endsWith() check if string ends with something
var str = "Kangaroo";
console.log(str.endsWith("roo")); // true
// string.charAt() return specific character
var str = "Kangaroo";
console.log(str[0]); // "K"
console.log(str.charAt(0)); // "K"
// string.charCodeAt() returns charCode
var str = "Kangaroo";
console.log(str.charCodeAt(0)); // charCode of "K" => 75
// string.fromCharCode() returns character from charCode
console.log(String.fromCharCode(75)); // show character of 75 charcode => "A"
// string.indexOf() return position of a character
var str = "Kangaroo";
console.log(str.indexOf("a")); // 1
// string.lastIndexOf() return position of a character
var str = "Kangaroo";
console.log(str.lastIndexOf("a")); // 4
// string.trim() remove spaces at beginning and end of a string
var str = " Kangaroo ";
console.log(str.trim()); // "Kangaroo"
console.log(str.trimStart()); // "Kangaroo "
console.log(str.trimEnd()); // " Kangaroo"
// string.slice() picks part of the string (start, end-1)
var str = "Kangaroo";
console.log("slice".slice(0, 3)); // "Kan"
// string.repeat() multiply a string !!IE
var str = "Kangaroo";
console.log(str.repeat(3)); // "KangarooKangarooKangaroo"
// string.toLowerCase()
var str = "Kangaroo";
console.log(str.toLowerCase()); // "kangaroo"
// string.toUpperCase()
var str = "Kangaroo";
console.log(str.toUpperCase()); // "KANGAROO"
// capitalize first letter
var str = "kangaroo";
str.charAt(0).toUpperCase() + str.slice(1); // Kangaroo
// string.replace() replace a string in a string
var str = "Salut, c'est chouette !";
console.log(str.replace("chouette", "cool")); // "Salut, c'est cool !"
// use replace to add spaces before uppercases; or smth else
var str = "myNameIsWhat";
console.log(str.replace(/([a-z])([A-Z])/g, "$1 $2")); // my Name Is What
console.log(str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()); // my-name-is-what
// return all character from a string
var word = "Kangaroo";
for (var i = 0; i < word.length; i++) {
console.log(word[i]);
}
// lots of process on a word
var word = "Kangaroo";
function countVowels(word) {
var vowels = 0;
for (var i = 0; i < word.length; i++) {
var letter = word[i].toLowerCase();
if ((letter === "a") || (letter === "e") || (letter === "i") || (letter === "o") || (letter === "u") || (letter === "y")) {
vowels++;
}
}