├── 02_Day_Basic_Type
└── README.md
├── CONTRIBUTING.md
└── README.md
/02_Day_Basic_Type/README.md:
--------------------------------------------------------------------------------
1 |
2 |
Basic
3 |
6 |
9 |
10 |
Author:
11 | Trust Onye
12 | January, 2023
13 |
14 |
15 |
16 |
17 |
18 | [<< Day 1](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
19 |
20 | 
21 |
22 | - [📔 Day 2](#-day-2)
23 | - [Data Types](#data-types)
24 | - [Primitive Data Types](#primitive-data-types)
25 | - [Non-Primitive Data Types](#non-primitive-data-types)
26 | - [Numbers](#numbers)
27 | - [Declaring Number Data Types](#declaring-number-data-types)
28 | - [Math Object](#math-object)
29 | - [Random Number Generator](#random-number-generator)
30 |
31 | - [Checking Data Types and Casting](#checking-data-types-and-casting)
32 | - [Checking Data Types](#checking-data-types)
33 | - [Changing Data Type (Casting)](#changing-data-type-casting)
34 | - [String to Int](#string-to-int)
35 | - [String to Float](#string-to-float)
36 | - [Float to Int](#float-to-int)
37 | - [💻 Day 2: Exercises](#-day-2-exercises)
38 | - [Exercise: Level 1](#exercise-level-1)
39 | - [Exercise: Level 2](#exercise-level-2)
40 | - [Exercises: Level 3](#exercises-level-3)
41 |
42 | # 📔 Day 2
43 |
44 | ## Data Types
45 |
46 | In the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two:
47 |
48 | 1. Primitive data types
49 | 2. Non-primitive data types(Object References)
50 |
51 | ### Primitive Data Types
52 |
53 | Primitive data types in JavaScript include:
54 |
55 | 1. Numbers - Integers, floats
56 | 2. Strings - Any data under single quote, double quote or backtick quote
57 | 3. Booleans - true or false value
58 | 4. Null - empty value or no value
59 | 5. Undefined - a declared variable without a value
60 | 6. Symbol - A unique value that can be generated by Symbol constructor
61 |
62 | Non-primitive data types in JavaScript includes:
63 |
64 | 1. Objects
65 | 2. Arrays
66 |
67 | Now, let us see what exactly primitive and non-primitive data types mean.
68 | _Primitive_ data types are immutable(non-modifiable) data types. Once a primitive data type is created we cannot modify it.
69 |
70 | **Example:**
71 |
72 | ```js
73 | let word = "JavaScript";
74 | ```
75 |
76 | If we try to modify the string stored in variable _word_, JavaScript should raise an error. Any data type under a single quote, double quote, or backtick quote is a string data type.
77 |
78 | ```js
79 | word[0] = "Y";
80 | ```
81 |
82 | This expression does not change the string stored in the variable _word_. So, we can say that strings are not modifiable or in other words immutable.
83 | Primitive data types are compared by its values. Let us compare different data values. See the example below:
84 |
85 | ```js
86 | let numOne = 3;
87 | let numTwo = 3;
88 |
89 | console.log(numOne == numTwo); // true
90 |
91 | let js = "JavaScript";
92 | let py = "Python";
93 |
94 | console.log(js == py); //false
95 |
96 | let lightOn = true;
97 | let lightOff = false;
98 |
99 | console.log(lightOn == lightOff); // false
100 | ```
101 |
102 | ### Non-Primitive Data Types
103 |
104 | _Non-primitive_ data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created.
105 | Let us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc.
106 |
107 | ```js
108 | let nums = [1, 2, 3];
109 | nums[0] = 10;
110 |
111 | console.log(nums); // [10, 2, 3]
112 | ```
113 |
114 | As you can see, an array, which is a non-primitive data type is mutable. Non-primitive data types cannot be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.
115 |
116 | ```js
117 | let nums = [1, 2, 3];
118 | let numbers = [1, 2, 3];
119 |
120 | console.log(nums == numbers); // false
121 |
122 | let userOne = {
123 | name: "Asabeneh",
124 | role: "teaching",
125 | country: "Finland",
126 | };
127 |
128 | let userTwo = {
129 | name: "Asabeneh",
130 | role: "teaching",
131 | country: "Finland",
132 | };
133 |
134 | console.log(userOne == userTwo); // false
135 | ```
136 |
137 | Rule of thumb, we do not compare non-primitive data types. Do not compare arrays, functions, or objects.
138 | Non-primitive values are referred to as reference types, because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.
139 |
140 | ```js
141 | let nums = [1, 2, 3];
142 | let numbers = nums;
143 |
144 | console.log(nums == numbers); // true
145 |
146 | let userOne = {
147 | name: "Asabeneh",
148 | role: "teaching",
149 | country: "Finland",
150 | };
151 |
152 | let userTwo = userOne;
153 |
154 | console.log(userOne == userTwo); // true
155 | ```
156 |
157 | If you have a hard time understanding the difference between primitive data types and non-primitive data types, you are not the only one. Calm down and just go to the next section and try to come back after some time. Now let us start the data types by number type.
158 |
159 | ## Numbers
160 |
161 | Numbers are integers and decimal values which can do all the arithmetic operations.
162 | Let's see some examples of Numbers.
163 |
164 | ### Declaring Number Data Types
165 |
166 | ```js
167 | let age = 35;
168 | const gravity = 9.81; // we use const for non-changing values, gravitational constant in m/s2
169 | let mass = 72; // mass in Kilogram
170 | const PI = 3.14; // pi a geometrical constant
171 |
172 | // More Examples
173 | const boilingPoint = 100; // temperature in oC, boiling point of water which is a constant
174 | const bodyTemp = 37; // oC average human body temperature, which is a constant
175 |
176 | console.log(age, gravity, mass, PI, boilingPoint, bodyTemp);
177 | ```
178 |
179 | ### Math Object
180 |
181 | In JavaScript the Math Object provides a lots of methods to work with numbers.
182 |
183 | ```js
184 | const PI = Math.PI;
185 |
186 | console.log(PI); // 3.141592653589793
187 |
188 | // Rounding to the closest number
189 | // if above .5 up if less 0.5 down rounding
190 |
191 | console.log(Math.round(PI)); // 3 to round values to the nearest number
192 |
193 | console.log(Math.round(9.81)); // 10
194 |
195 | console.log(Math.floor(PI)); // 3 rounding down
196 |
197 | console.log(Math.ceil(PI)); // 4 rounding up
198 |
199 | console.log(Math.min(-5, 3, 20, 4, 5, 10)); // -5, returns the minimum value
200 |
201 | console.log(Math.max(-5, 3, 20, 4, 5, 10)); // 20, returns the maximum value
202 |
203 | const randNum = Math.random(); // creates random number between 0 to 0.999999
204 | console.log(randNum);
205 |
206 | // Let us create random number between 0 to 10
207 |
208 | const num = Math.floor(Math.random() * 11); // creates random number between 0 and 10
209 | console.log(num);
210 |
211 | //Absolute value
212 | console.log(Math.abs(-10)); // 10
213 |
214 | //Square root
215 | console.log(Math.sqrt(100)); // 10
216 |
217 | console.log(Math.sqrt(2)); // 1.4142135623730951
218 |
219 | // Power
220 | console.log(Math.pow(3, 2)); // 9
221 |
222 | console.log(Math.E); // 2.718
223 |
224 | // Logarithm
225 | // Returns the natural logarithm with base E of x, Math.log(x)
226 | console.log(Math.log(2)); // 0.6931471805599453
227 | console.log(Math.log(10)); // 2.302585092994046
228 |
229 | // Returns the natural logarithm of 2 and 10 respectively
230 | console.log(Math.LN2); // 0.6931471805599453
231 | console.log(Math.LN10); // 2.302585092994046
232 |
233 | // Trigonometry
234 | Math.sin(0);
235 | Math.sin(60);
236 |
237 | Math.cos(0);
238 | Math.cos(60);
239 | ```
240 |
241 |
242 | The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...
243 |
244 | ```js
245 | let randomNum = Math.random(); // generates 0 to 0.999...
246 | ```
247 |
248 | Now, let us see how we can use random() method to generate a random number between 0 and 10:
249 |
250 | ```js
251 | let randomNum = Math.random(); // generates 0 to 0.999
252 | let numBtnZeroAndTen = randomNum * 11;
253 |
254 | console.log(numBtnZeroAndTen); // this gives: min 0 and max 10.99
255 |
256 | let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen);
257 | console.log(randomNumRoundToFloor); // this gives between 0 and 10
258 | ```
259 |
260 | ## Strings
261 |
262 | Strings are texts, which are under **_single_** , **_double_**, **_back-tick_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double quote, or backtick quote.
263 | Let's see some examples of strings:
264 |
265 | ```js
266 | let space = " "; // an empty space string
267 | let firstName = "Asabeneh";
268 | let lastName = "Yetayeh";
269 | let country = "Finland";
270 | let city = "Helsinki";
271 | let language = "JavaScript";
272 | let job = "teacher";
273 | let quote = "The saying,'Seeing is Believing' is not correct in 2020.";
274 | let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`;
275 | ```
276 |
277 | ### String Concatenation
278 |
279 | Connecting two or more strings together is called concatenation.
280 | Using the strings declared in the previous String section:
281 |
282 | ```js
283 | let fullName = firstName + space + lastName; // concatenation, merging two string together.
284 | console.log(fullName);
285 | ```
286 |
287 | ```sh
288 | Asabeneh Yetayeh
289 | ```
290 |
291 | We can concatenate strings in different ways.
292 |
293 | #### Concatenating Using Addition Operator
294 |
295 | Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the ES6 template strings (explained later on).
296 |
297 | ```js
298 | // Declaring different variables of different data types
299 | let space = " ";
300 | let firstName = "Asabeneh";
301 | let lastName = "Yetayeh";
302 | let country = "Finland";
303 | let city = "Helsinki";
304 | let language = "JavaScript";
305 | let job = "teacher";
306 | let age = 250;
307 |
308 | let fullName = firstName + space + lastName;
309 | let personInfoOne = fullName + ". I am " + age + ". I live in " + country; // ES5 string addition
310 |
311 | console.log(personInfoOne);
312 | ```
313 |
314 | ```sh
315 | Asabeneh Yetayeh. I am 250. I live in Finland
316 | ```
317 |
318 | #### Long Literal Strings
319 |
320 | A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\\) at the end of each line to indicate that the string will continue on the next line.
321 | **Example:**
322 |
323 | ```js
324 | const paragraph =
325 | "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\
326 | I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \
327 | Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \
328 | In the end of 2019, I was thinking to expand my teaching and to reach \
329 | to global audience and I started a Python challenge from November 20 - December 19.\
330 | It was one of the most rewarding and inspiring experience.\
331 | Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
332 | I hope you are enjoying too.";
333 |
334 | console.log(paragraph);
335 | ```
336 |
337 | #### Escape Sequences in Strings
338 |
339 | In JavaScript and other programming languages \ followed by some characters is an escape sequence. Let's see the most common escape characters:
340 |
341 | - \n: new line
342 | - \t: Tab, means 8 spaces
343 | - \\\\: Back slash
344 | - \\': Single quote (')
345 | - \\": Double quote (")
346 |
347 | ```js
348 | console.log(
349 | "I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?"
350 | ); // line break
351 | console.log("Days\tTopics\tExercises");
352 | console.log("Day 1\t3\t5");
353 | console.log("Day 2\t3\t5");
354 | console.log("Day 3\t3\t5");
355 | console.log("Day 4\t3\t5");
356 | console.log("This is a backslash symbol (\\)"); // To write a backslash
357 | console.log('In every programming language it starts with "Hello, World!"');
358 | console.log("In every programming language it starts with 'Hello, World!'");
359 | console.log("The saying 'Seeing is Believing' isn't correct in 2020");
360 | ```
361 |
362 | Output in console:
363 |
364 | ```sh
365 | I hope everyone is enjoying the 30 Days Of JavaScript challenge.
366 | Do you ?
367 | Days Topics Exercises
368 | Day 1 3 5
369 | Day 2 3 5
370 | Day 3 3 5
371 | Day 4 3 5
372 | This is a backslash symbol (\)
373 | In every programming language it starts with "Hello, World!"
374 | In every programming language it starts with 'Hello, World!'
375 | The saying 'Seeing is Believing' isn't correct in 2020
376 | ```
377 |
378 | #### Template Literals (Template Strings)
379 |
380 | To create a template strings, we use two back-ticks. We can inject data as expressions inside a template string. To inject data, we enclose the expression with a curly bracket({}) preceded by a $ sign. See the syntax below.
381 |
382 | ```js
383 | //Syntax
384 | `String literal text``String literal text ${expression}`;
385 | ```
386 |
387 | **Example: 1**
388 |
389 | ```js
390 | console.log(`The sum of 2 and 3 is 5`); // statically writing the data
391 | let a = 2;
392 | let b = 3;
393 | console.log(`The sum of ${a} and ${b} is ${a + b}`); // injecting the data dynamically
394 | ```
395 |
396 | **Example:2**
397 |
398 | ```js
399 | let firstName = "Asabeneh";
400 | let lastName = "Yetayeh";
401 | let country = "Finland";
402 | let city = "Helsinki";
403 | let language = "JavaScript";
404 | let job = "teacher";
405 | let age = 250;
406 | let fullName = firstName + " " + lastName;
407 |
408 | let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.`; //ES6 - String interpolation method
409 | let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`;
410 | console.log(personInfoTwo);
411 | console.log(personInfoThree);
412 | ```
413 |
414 | ```sh
415 | I am Asabeneh Yetayeh. I am 250. I live in Finland.
416 | I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.
417 | ```
418 |
419 | Using a string template or string interpolation method, we can add expressions, which could be a value, or some operations (comparison, arithmetic operations, ternary operation).
420 |
421 | ```js
422 | let a = 2;
423 | let b = 3;
424 | console.log(`${a} is greater than ${b}: ${a > b}`);
425 | ```
426 |
427 | ```sh
428 | 2 is greater than 3: false
429 | ```
430 |
431 | ### String Methods
432 |
433 | Everything in JavaScript is an object. A string is a primitive data type that means we can not modify it once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
434 |
435 | 1. _length_: The string _length_ method returns the number of characters in a string included empty space.
436 |
437 | **Example:**
438 |
439 | ```js
440 | let js = "JavaScript";
441 | console.log(js.length); // 10
442 | let firstName = "Asabeneh";
443 | console.log(firstName.length); // 8
444 | ```
445 |
446 | 2. _Accessing characters in a string_: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is the length of the string minus one.
447 |
448 | 
449 |
450 | Let us access different characters in 'JavaScript' string.
451 |
452 | ```js
453 | let string = "JavaScript";
454 | let firstLetter = string[0];
455 |
456 | console.log(firstLetter); // J
457 |
458 | let secondLetter = string[1]; // a
459 | let thirdLetter = string[2];
460 | let lastLetter = string[9];
461 |
462 | console.log(lastLetter); // t
463 |
464 | let lastIndex = string.length - 1;
465 |
466 | console.log(lastIndex); // 9
467 | console.log(string[lastIndex]); // t
468 | ```
469 |
470 | 3. _toUpperCase()_: this method changes the string to uppercase letters.
471 |
472 | ```js
473 | let string = "JavaScript";
474 |
475 | console.log(string.toUpperCase()); // JAVASCRIPT
476 |
477 | let firstName = "Asabeneh";
478 |
479 | console.log(firstName.toUpperCase()); // ASABENEH
480 |
481 | let country = "Finland";
482 |
483 | console.log(country.toUpperCase()); // FINLAND
484 | ```
485 |
486 | 4. _toLowerCase()_: this method changes the string to lowercase letters.
487 |
488 | ```js
489 | let string = "JavasCript";
490 |
491 | console.log(string.toLowerCase()); // javascript
492 |
493 | let firstName = "Asabeneh";
494 |
495 | console.log(firstName.toLowerCase()); // asabeneh
496 |
497 | let country = "Finland";
498 |
499 | console.log(country.toLowerCase()); // finland
500 | ```
501 |
502 | 5. _substr()_: It takes two arguments, the starting index and number of characters to slice.
503 |
504 | ```js
505 | let string = "JavaScript";
506 | console.log(string.substr(4, 6)); // Script
507 |
508 | let country = "Finland";
509 | console.log(country.substr(3, 4)); // land
510 | ```
511 |
512 | 6. _substring()_: It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index.
513 |
514 | ```js
515 | let string = "JavaScript";
516 |
517 | console.log(string.substring(0, 4)); // Java
518 | console.log(string.substring(4, 10)); // Script
519 | console.log(string.substring(4)); // Script
520 |
521 | let country = "Finland";
522 |
523 | console.log(country.substring(0, 3)); // Fin
524 | console.log(country.substring(3, 7)); // land
525 | console.log(country.substring(3)); // land
526 | ```
527 |
528 | 7. _split()_: The split method splits a string at a specified place.
529 |
530 | ```js
531 | let string = "30 Days Of JavaScript";
532 |
533 | console.log(string.split()); // Changes to an array -> ["30 Days Of JavaScript"]
534 | console.log(string.split(" ")); // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
535 |
536 | let firstName = "Asabeneh";
537 |
538 | console.log(firstName.split()); // Change to an array - > ["Asabeneh"]
539 | console.log(firstName.split("")); // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"]
540 |
541 | let countries = "Finland, Sweden, Norway, Denmark, and Iceland";
542 |
543 | console.log(countries.split(",")); // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
544 | console.log(countries.split(", ")); // ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
545 | ```
546 |
547 | 8. _trim()_: Removes trailing space in the beginning or the end of a string.
548 |
549 | ```js
550 | let string = " 30 Days Of JavaScript ";
551 |
552 | console.log(string);
553 | console.log(string.trim(" "));
554 |
555 | let firstName = " Asabeneh ";
556 |
557 | console.log(firstName);
558 | console.log(firstName.trim()); // still removes spaces at the beginning and the end of the string
559 | ```
560 |
561 | ```sh
562 | 30 Days Of JavasCript
563 | 30 Days Of JavasCript
564 | Asabeneh
565 | Asabeneh
566 | ```
567 |
568 | 9. _includes()_: It takes a substring argument and it checks if substring argument exists in the string. _includes()_ returns a boolean. If a substring exist in a string, it returns true, otherwise it returns false.
569 |
570 | ```js
571 | let string = "30 Days Of JavaScript";
572 |
573 | console.log(string.includes("Days")); // true
574 | console.log(string.includes("days")); // false - it is case sensitive!
575 | console.log(string.includes("Script")); // true
576 | console.log(string.includes("script")); // false
577 | console.log(string.includes("java")); // false
578 | console.log(string.includes("Java")); // true
579 |
580 | let country = "Finland";
581 |
582 | console.log(country.includes("fin")); // false
583 | console.log(country.includes("Fin")); // true
584 | console.log(country.includes("land")); // true
585 | console.log(country.includes("Land")); // false
586 | ```
587 |
588 | 10. _replace()_: takes as a parameter the old substring and a new substring.
589 |
590 | ```js
591 | string.replace(oldsubstring, newsubstring);
592 | ```
593 |
594 | ```js
595 | let string = "30 Days Of JavaScript";
596 | console.log(string.replace("JavaScript", "Python")); // 30 Days Of Python
597 |
598 | let country = "Finland";
599 | console.log(country.replace("Fin", "Noman")); // Nomanland
600 | ```
601 |
602 | 11. _charAt()_: Takes index and it returns the value at that index
603 |
604 | ```js
605 | string.charAt(index);
606 | ```
607 |
608 | ```js
609 | let string = "30 Days Of JavaScript";
610 | console.log(string.charAt(0)); // 3
611 |
612 | let lastIndex = string.length - 1;
613 | console.log(string.charAt(lastIndex)); // t
614 | ```
615 |
616 | 12. _charCodeAt()_: Takes index and it returns char code (ASCII number) of the value at that index
617 |
618 | ```js
619 | string.charCodeAt(index);
620 | ```
621 |
622 | ```js
623 | let string = "30 Days Of JavaScript";
624 | console.log(string.charCodeAt(3)); // D ASCII number is 68
625 |
626 | let lastIndex = string.length - 1;
627 | console.log(string.charCodeAt(lastIndex)); // t ASCII is 116
628 | ```
629 |
630 | 13. _indexOf()_: Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
631 |
632 | ```js
633 | string.indexOf(substring);
634 | ```
635 |
636 | ```js
637 | let string = "30 Days Of JavaScript";
638 |
639 | console.log(string.indexOf("D")); // 3
640 | console.log(string.indexOf("Days")); // 3
641 | console.log(string.indexOf("days")); // -1
642 | console.log(string.indexOf("a")); // 4
643 | console.log(string.indexOf("JavaScript")); // 11
644 | console.log(string.indexOf("Script")); //15
645 | console.log(string.indexOf("script")); // -1
646 | ```
647 |
648 | 14. _lastIndexOf()_: Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
649 |
650 | ```js
651 | //syntax
652 | string.lastIndexOf(substring);
653 | ```
654 |
655 | ```js
656 | let string =
657 | "I love JavaScript. If you do not love JavaScript what else can you love.";
658 |
659 | console.log(string.lastIndexOf("love")); // 67
660 | console.log(string.lastIndexOf("you")); // 63
661 | console.log(string.lastIndexOf("JavaScript")); // 38
662 | ```
663 |
664 | 15. _concat()_: it takes many substrings and joins them.
665 |
666 | ```js
667 | string.concat(substring, substring, substring);
668 | ```
669 |
670 | ```js
671 | let string = "30";
672 | console.log(string.concat("Days", "Of", "JavaScript")); // 30DaysOfJavaScript
673 |
674 | let country = "Fin";
675 | console.log(country.concat("land")); // Finland
676 | ```
677 |
678 | 16. _startsWith_: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
679 |
680 | ```js
681 | //syntax
682 | string.startsWith(substring);
683 | ```
684 |
685 | ```js
686 | let string = "Love is the best to in this world";
687 |
688 | console.log(string.startsWith("Love")); // true
689 | console.log(string.startsWith("love")); // false
690 | console.log(string.startsWith("world")); // false
691 |
692 | let country = "Finland";
693 |
694 | console.log(country.startsWith("Fin")); // true
695 | console.log(country.startsWith("fin")); // false
696 | console.log(country.startsWith("land")); // false
697 | ```
698 |
699 | 17. _endsWith_: it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean(true or false).
700 |
701 | ```js
702 | string.endsWith(substring);
703 | ```
704 |
705 | ```js
706 | let string = "Love is the most powerful feeling in the world";
707 |
708 | console.log(string.endsWith("world")); // true
709 | console.log(string.endsWith("love")); // false
710 | console.log(string.endsWith("in the world")); // true
711 |
712 | let country = "Finland";
713 |
714 | console.log(country.endsWith("land")); // true
715 | console.log(country.endsWith("fin")); // false
716 | console.log(country.endsWith("Fin")); // false
717 | ```
718 |
719 | 18. _search_: it takes a substring as an argument and it returns the index of the first match. The search value can be a string or a regular expression pattern.
720 |
721 | ```js
722 | string.search(substring);
723 | ```
724 |
725 | ```js
726 | let string =
727 | "I love JavaScript. If you do not love JavaScript what else can you love.";
728 | console.log(string.search("love")); // 2
729 | console.log(string.search(/javascript/gi)); // 7
730 | ```
731 |
732 | 19. _match_: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
733 |
734 | ```js
735 | let string = "love";
736 | let patternOne = /love/; // with out any flag
737 | let patternTwo = /love/gi; // g-means to search in the whole text, i - case insensitive
738 | ```
739 |
740 | Match syntax
741 |
742 | ```js
743 | // syntax
744 | string.match(substring);
745 | ```
746 |
747 | ```js
748 | let string =
749 | "I love JavaScript. If you do not love JavaScript what else can you love.";
750 | console.log(string.match("love"));
751 | ```
752 |
753 | ```sh
754 | ["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
755 | ```
756 |
757 | ```js
758 | let pattern = /love/gi;
759 | console.log(string.match(pattern)); // ["love", "love", "love"]
760 | ```
761 |
762 | Let us extract numbers from text using a regular expression. This is not the regular expression section, do not panic! We will cover regular expressions later on.
763 |
764 | ```js
765 | let txt =
766 | "In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge";
767 | let regEx = /\d+/;
768 |
769 | // d with escape character means d not a normal d instead acts a digit
770 | // + means one or more digit numbers,
771 | // if there is g after that it means global, search everywhere.
772 |
773 | console.log(txt.match(regEx)); // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
774 | console.log(txt.match(/\d+/g)); // ["2019", "30", "2020"]
775 | ```
776 |
777 | 20. _repeat()_: it takes a number as argument and it returns the repeated version of the string.
778 |
779 | ```js
780 | string.repeat(n);
781 | ```
782 |
783 | ```js
784 | let string = "love";
785 | console.log(string.repeat(10)); // lovelovelovelovelovelovelovelovelovelove
786 | ```
787 |
788 | ## Checking Data Types and Casting
789 |
790 | ### Checking Data Types
791 |
792 | To check the data type of a certain variable we use the _typeof_ method.
793 |
794 | **Example:**
795 |
796 | ```js
797 | // Different javascript data types
798 | // Let's declare different data types
799 |
800 | let firstName = "Asabeneh"; // string
801 | let lastName = "Yetayeh"; // string
802 | let country = "Finland"; // string
803 | let city = "Helsinki"; // string
804 | let age = 250; // number, it is not my real age, do not worry about it
805 | let job; // undefined, because a value was not assigned
806 |
807 | console.log(typeof "Asabeneh"); // string
808 | console.log(typeof firstName); // string
809 | console.log(typeof 10); // number
810 | console.log(typeof 3.14); // number
811 | console.log(typeof true); // boolean
812 | console.log(typeof false); // boolean
813 | console.log(typeof NaN); // number
814 | console.log(typeof job); // undefined
815 | console.log(typeof undefined); // undefined
816 | console.log(typeof null); // object
817 | ```
818 |
819 | ### Changing Data Type (Casting)
820 |
821 | - Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
822 | When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
823 |
824 | #### String to Int
825 |
826 | We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
827 | We can convert string to number using the following methods:
828 |
829 | - parseInt()
830 | - Number()
831 | - Plus sign(+)
832 |
833 | ```js
834 | let num = "10";
835 | let numInt = parseInt(num);
836 | console.log(numInt); // 10
837 | ```
838 |
839 | ```js
840 | let num = "10";
841 | let numInt = Number(num);
842 |
843 | console.log(numInt); // 10
844 | ```
845 |
846 | ```js
847 | let num = "10";
848 | let numInt = +num;
849 |
850 | console.log(numInt); // 10
851 | ```
852 |
853 | #### String to Float
854 |
855 | We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
856 | We can convert string float to number using the following methods:
857 |
858 | - parseFloat()
859 | - Number()
860 | - Plus sign(+)
861 |
862 | ```js
863 | let num = "9.81";
864 | let numFloat = parseFloat(num);
865 |
866 | console.log(numFloat); // 9.81
867 | ```
868 |
869 | ```js
870 | let num = "9.81";
871 | let numFloat = Number(num);
872 |
873 | console.log(numFloat); // 9.81
874 | ```
875 |
876 | ```js
877 | let num = "9.81";
878 | let numFloat = +num;
879 |
880 | console.log(numFloat); // 9.81
881 | ```
882 |
883 | #### Float to Int
884 |
885 | We can convert float numbers to integers.
886 | We use the following method to convert float to int:
887 |
888 | - parseInt()
889 |
890 | ```js
891 | let num = 9.81;
892 | let numInt = parseInt(num);
893 |
894 | console.log(numInt); // 9
895 | ```
896 |
897 | 🌕 You are awesome. You have just completed day 2 challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle.
898 |
899 | ## 💻 Day 2: Exercises
900 |
901 | ### Exercise: Level 1
902 |
903 | 1. Declare a variable named challenge and assign it to an initial value **'30 Days Of JavaScript'**.
904 | 2. Print the string on the browser console using **console.log()**
905 | 3. Print the **length** of the string on the browser console using _console.log()_
906 | 4. Change all the string characters to capital letters using **toUpperCase()** method
907 | 5. Change all the string characters to lowercase letters using **toLowerCase()** method
908 | 6. Cut (slice) out the first word of the string using **substr()** or **substring()** method
909 | 7. Slice out the phrase _Days Of JavaScript_ from _30 Days Of JavaScript_.
910 | 8. Check if the string contains a word **Script** using **includes()** method
911 | 9. Split the **string** into an **array** using **split()** method
912 | 10. Split the string 30 Days Of JavaScript at the space using **split()** method
913 | 11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' **split** the string at the comma and change it to an array.
914 | 12. Change 30 Days Of JavaScript to 30 Days Of Python using **replace()** method.
915 | 13. What is character at index 15 in '30 Days Of JavaScript' string? Use **charAt()** method.
916 | 14. What is the character code of J in '30 Days Of JavaScript' string using **charCodeAt()**
917 | 15. Use **indexOf** to determine the position of the first occurrence of **a** in 30 Days Of JavaScript
918 | 16. Use **lastIndexOf** to determine the position of the last occurrence of **a** in 30 Days Of JavaScript.
919 | 17. Use **indexOf** to find the position of the first occurrence of the word **because** in the following sentence:**'You cannot end a sentence with because because because is a conjunction'**
920 | 18. Use **lastIndexOf** to find the position of the last occurrence of the word **because** in the following sentence:**'You cannot end a sentence with because because because is a conjunction'**
921 | 19. Use **search** to find the position of the first occurrence of the word **because** in the following sentence:**'You cannot end a sentence with because because because is a conjunction'**
922 | 20. Use **trim()** to remove any trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
923 | 21. Use **startsWith()** method with the string _30 Days Of JavaScript_ and make the result true
924 | 22. Use **endsWith()** method with the string _30 Days Of JavaScript_ and make the result true
925 | 23. Use **match()** method to find all the **a**’s in 30 Days Of JavaScript
926 | 24. Use **concat()** and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
927 | 25. Use **repeat()** method to print 30 Days Of JavaScript 2 times
928 |
929 | ### Exercise: Level 2
930 |
931 | 1. Using console.log() print out the following statement:
932 |
933 | ```sh
934 | The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
935 | ```
936 |
937 | 2. Using console.log() print out the following quote by Mother Teresa:
938 |
939 | ```sh
940 | "Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
941 | ```
942 |
943 | 3. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
944 | 4. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
945 | 5. Check if 'on' is found in both python and jargon
946 | 6. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
947 | 7. Generate a random number between 0 and 100 inclusively.
948 | 8. Generate a random number between 50 and 100 inclusively.
949 | 9. Generate a random number between 0 and 255 inclusively.
950 | 10. Access the 'JavaScript' string characters using a random number.
951 | 11. Use console.log() and escape characters to print the following pattern.
952 |
953 | ```js
954 | 1 1 1 1 1
955 | 2 1 2 4 8
956 | 3 1 3 9 27
957 | 4 1 4 16 64
958 | 5 1 5 25 125
959 | ```
960 |
961 | 12. Use **substr** to slice out the phrase **because because because** from the following sentence:**'You cannot end a sentence with because because because is a conjunction'**
962 |
963 | ### Exercises: Level 3
964 |
965 | 1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word **love** in this sentence.
966 | 2. Use **match()** to count the number of all **because** in the following sentence:**'You cannot end a sentence with because because because is a conjunction'**
967 | 3. Clean the following text and find the most frequent word (hint, use replace and regular expressions).
968 |
969 | ```js
970 | const sentence =
971 | "%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching";
972 | ```
973 |
974 | 🎉 CONGRATULATIONS ! 🎉
975 |
976 | [<< Day 1](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
977 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 | # Lets learn Typescript Together
3 | I think that learning together and sharing our knowledge with others is an effective way to learn new things.
4 |
5 | ## 💥 Ways to
6 | - Document what you newly learn
7 | - Code Examples
8 | - Code Testing
9 |
10 | ## 💥 How to Contribute
11 |
12 | [](https://github.com/code-with-onye/30-days-of-Typescript/pulls)
13 | [](https://github.com/code-with-onye/30-days-of-Typescript/)
14 |
15 | - Take a look at the existing [Issues](https://github.com/code-with-onye/30-days-of-Typescript/issues) or [create a new issue](https://github.com/code-with-onye/30-days-of-Typescript/issues/new/choose)!
16 | - [Fork the Repo](https://github.com/code-with-onye/30-days-of-Typescript/fork). Then, create a branch for any issue that you are working on. Finally, commit your work.
17 | - Create a **[Pull Request](https://github.com/code-with-onye/30-days-of-Typescript/compare)** (_PR_), which will be promptly reviewed and given suggestions for improvements by the community.
18 | - Add screenshots or screen captures to your Pull Request to help us understand the effects of the changes proposed in your PR.
19 |
20 | ---
21 |
22 | ## ⭐ HOW TO MAKE A PULL REQUEST:
23 |
24 | **1.** Start by making a Fork of the [**30-days-of-Typescript**](https://github.com/code-with-onye/30-days-of-Typescript) repository. Click on the
Fork symbol at the top right corner.
25 |
26 | **2.** Clone your new fork of the repository in the terminal/CLI on your computer with the following command:
27 |
28 | ```bash
29 | git clone https://github.com//30-days-of-Typescript
30 | ```
31 |
32 | **3.** Navigate to the newly created LinkFree project directory:
33 |
34 | ```bash
35 | cd 30-days-of-Typescript
36 | ```
37 |
38 | **4.** Set upstream command:
39 |
40 | ```bash
41 | git remote add upstream https://github.com/code-with-onye/30-days-of-Typescript.git
42 | ```
43 |
44 | **5.** Create a new branch:
45 |
46 | ```bash
47 | git checkout -b YourBranchName
48 | ```
49 |
50 | **6.** Sync your fork or your local repository with the origin repository:
51 |
52 | - In your forked repository, click on "Fetch upstream"
53 | - Click "Fetch and merge"
54 |
55 | ### Alternatively, Git CLI way to Sync forked repository with origin repository:
56 |
57 | ```bash
58 | git fetch upstream
59 | ```
60 |
61 | ```bash
62 | git merge upstream/main
63 | ```
64 |
65 | ### [Github Docs](https://docs.github.com/en/github/collaborating-with-pull-requests/addressing-merge-conflicts/resolving-a-merge-conflict-on-github) for Syncing
66 |
67 | **7.** Make your changes to the source code.
68 |
69 | **8.** Stage your changes:
70 |
71 | ⚠️ **Make sure** not to commit `package.json` or `package-lock.json` file
72 |
73 | ⚠️ **Make sure** not to run the commands `git add .` or `git add *`
74 |
75 | > Instead, stage your changes for each file/folder
76 | >
77 | > By using public path it means it will add all files and folders under that folder, it is better to be specific
78 |
79 | ```bash
80 | git add public
81 | ```
82 |
83 | _or_
84 |
85 | ```bash
86 | git add ""
87 | ```
88 |
89 | **9.** Commit your changes:
90 |
91 | ```bash
92 | git commit -m ""
93 | ```
94 |
95 | **10.** Push your local commits to the remote repository:
96 |
97 | ```bash
98 | git push origin YourBranchName
99 | ```
100 |
101 | **11.** Create a [Pull Request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)!
102 |
103 | **12.** **Congratulations!** You've made your first contribution to [**30-days-of-Typescript**](https://github.com/code-with-onye/30-days-of-Typescript/graphs/contributors)! 🙌🏼
104 |
105 | **_:trophy: After this, the maintainers will review the PR and will merge it if it helps move the LinkFree project forward. Otherwise, it will be given constructive feedback and suggestions for the changes needed to add the PR to the codebase._**
106 |
107 |
108 | ---
109 |
110 | ## Style Guide for Git Commit Messages :memo:
111 |
112 | **How you can add more value to your contribution logs:**
113 |
114 | - Use the present tense. (Example: "Add feature" instead of "Added feature")
115 | - Use the imperative mood. (Example: "Move item to...", instead of "Moves item to...")
116 | - Limit the first line (also called the Subject Line) to _50 characters or less_.
117 | - Capitalize the Subject Line.
118 | - Separate subject from body with a blank line.
119 | - Do not end the subject line with a period.
120 | - Wrap the body at _72 characters_.
121 | - Use the body to explain the _what_, _why_, _vs_, and _how_.
122 | - Reference [Issues](https://github.com/code-with-onye/30-days-of-Typescript/issues) and [Pull Requests](https://github.com/code-with-onye/30-days-of-Typescript/pulls) liberally after the first line.
123 |
124 | ---
125 |
126 | ## 💥 Issue
127 |
128 | In order to discuss changes, you are welcome to [open an issue](https://github.com/code-with-onye/30-days-of-Typescript/issues/new/choose) about what you would like to contribute. Enhancements are always encouraged and appreciated.
129 |
130 | ## All the best! 🥇
131 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 30 Days of Typescript
2 |
3 | 
4 |
5 | | # Day | Topics |
6 | | ----- | :----------------------------------------------------------------------------------------------: |
7 | | 01 | [Getting Started](./README.md) |
8 | | 02 | [Basic Types](./02_Day_Basic_Type/README.md) |
9 | | 03 | [Control Flow Statements](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
10 | | 04 | [Functions](./04_Day_Conditionals/04_day_conditionals.md) |
11 | | 05 | [Classes](./05_Day_Arrays/05_day_arrays.md) |
12 | | 06 | [Functions](./06_Day_Loops/06_day_loops.md) |
13 | | 07 | [Interfaces](./07_Day_Functions/07_day_functions.md) |
14 | | 08 | [Interfaces](./08_Day_Objects/08_day_objects.md) |
15 | | 09 | [Advanced Types](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
16 | | 10 | [Generics](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
17 | | 11 | [TypeScript Modules](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
18 | | 12 | [Node.js Typescript](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
19 |
20 | 🧡🧡🧡 HAPPY CODING 🧡🧡🧡
21 |
22 | ---
23 | ## Contribute
24 |
25 | I think that learning together and sharing our knowledge with others is an effective way to learn new things.
26 | kindly [Contribute](https://github.com/code-with-onye/30-days-of-Typescript/blob/main/CONTRIBUTING.md)
27 |
28 | ## 🛡️ License
29 |
30 | 30-days-of-Typescript is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
31 |
32 | ## 💪 Thanks to all Contributors
33 |
34 | Thanks a lot for spending your time helping 30-days-of-Typescript grow. Thanks a lot! Keep rocking 🍻
35 |
36 | [](https://github.com/code-with-onye/30-days-of-Typescript/graphs/contributors)
37 |
38 | ## 🙏 Support
39 |
40 | This project needs a ⭐️ from you. Don't forget to leave a star ⭐️
41 |
--------------------------------------------------------------------------------