💯 Tries: 10
25 |26 | 🥇 Highscore: 0 27 |
28 |├── .gitignore
├── .vscode
└── settings.json
├── 01-Fundamentals-Part-1
├── 00_introduction
│ └── README.md
├── 01_hello_world
│ ├── Hello_world.js
│ └── README.md
├── 02_javascript_linking
│ ├── README.md
│ └── script.js
├── 03_values_variables
│ ├── README.md
│ └── script.js
├── 04_data_types
│ ├── README.md
│ └── script.js
├── 05_let_const_var
│ ├── README.md
│ └── script.js
├── 06_basic_operators
│ ├── README.md
│ └── script.js
├── 07_operator_precedence
│ ├── README.md
│ └── script.js
├── 08_coding_challenge_1
│ ├── README.md
│ └── script.js
├── 09_strings_template_literals
│ ├── README.md
│ └── script.js
├── 10_taking_decisions_if_else_statements
│ ├── README.md
│ └── script.js
├── 11_coding_challenge_2
│ ├── README.md
│ └── script.js
├── 12_type_conversion_coercion
│ ├── README.md
│ └── script.js
├── 13_truthy_falsy_values
│ ├── README.md
│ └── script.js
├── 14_equality_operators
│ ├── README.md
│ └── script.js
├── 15_boolean_logic
│ ├── README.md
│ └── script.js
├── 16_logical_operators
│ ├── README.md
│ └── script.js
├── 17_coding_challenge_3
│ ├── README.md
│ └── script.js
├── 18_switch_statement
│ ├── README.md
│ └── script.js
├── 19_statements_expressions
│ ├── README.md
│ └── script.js
├── 20_conditional_ternary_operator
│ ├── README.md
│ └── script.js
├── 21_coding_challenge_4
│ ├── README.md
│ └── script.js
├── 22_javascript_releases_ES5_ES6+_ESNext
│ └── README.md
└── assignment.js
├── 02-Fundamentals-Part-2
├── 00_strict_mode
│ ├── README.md
│ └── script.js
├── 01_functions
│ ├── README.md
│ └── script.js
├── 02_functions_declarations_expressions
│ ├── README.md
│ └── script.js
├── 03_arrow_function
│ ├── README.md
│ └── script.js
├── 04_functions_calling_other_functions
│ ├── README.md
│ └── script.js
├── 05_reviewing_functions
│ ├── README.md
│ └── script.js
├── 06_coding_challenge
│ ├── README.md
│ └── script.js
├── 07_introduction_to_arrays
│ ├── README.md
│ └── script.js
├── 08_basic_array_operations
│ ├── README.md
│ └── script.js
├── 09_coding_challenge
│ ├── README.md
│ └── script.js
├── 10_introduction_to_objects
│ ├── README.md
│ └── script.js
├── 11_dots_brackets_notation
│ ├── README.md
│ └── script.js
├── 12_object_methods
│ ├── README.md
│ └── script.js
├── 13_coding_challenge
│ ├── README.md
│ └── script.js
├── 14_Iteration_the_for_loop
│ ├── README.md
│ └── script.js
├── 15_looping_arrays_breaking_continuing
│ ├── README.md
│ └── script.js
├── 16_looping_backwards_and_loops_in_loops
│ └── script.js
├── 17_while_loop
│ └── script.js
└── 18_coding_challenge
│ ├── README.md
│ └── script.js
├── 03_Developers-Skills
├── How_to_solve_problems.md
├── challenge.js
└── script.js
├── 05-Guess-My-Number
├── .prettierrc
├── README.md
├── cheer.mp3
├── index.html
├── script.js
└── style.css
├── 06-Modal-Window
├── .prettierrc
├── README.md
├── favicon.ico
├── index.html
├── script.js
└── style.css
├── 07-Pig-Game
├── .prettierrc
├── README.md
├── favicon.ico
├── images
│ ├── dice-1.png
│ ├── dice-2.png
│ ├── dice-3.png
│ ├── dice-4.png
│ ├── dice-5.png
│ └── dice-6.png
├── index.html
├── pig-game-flowchart.png
├── script.js
└── style.css
├── 08-behind-the-scenes
├── README.md
└── script.js
├── 09-Data-Structure-Modern-Operators-and-Strings
├── README.md
├── challenge.js
├── favicon.ico
└── script.js
├── 10-A_Closer_Look_At_Functions
├── README.md
├── challenge.js
├── favicon.ico
├── index.html
├── script.js
└── style.css
├── 11_Working_with_Arrays
├── .prettierrc
├── Bankist-flowchart.png
├── README.md
├── challenge.js
├── icon.png
├── index.html
├── logo.png
├── script.js
└── style.css
├── 12_Numbers_Dates_Timers_Bankist
├── .prettierrc
├── Bankist-flowchart.png
├── buzz.mp3
├── icon.png
├── index.html
├── logo.png
├── script.js
├── style.css
└── timer.html
├── 13-Advanced-Dom-Events
├── .prettierrc
├── README.md
├── img
│ ├── card-lazy.jpg
│ ├── card.jpg
│ ├── digital-lazy.jpg
│ ├── digital.jpg
│ ├── grow-lazy.jpg
│ ├── grow.jpg
│ ├── hero.png
│ ├── icon.png
│ ├── icons.svg
│ ├── img-1.jpg
│ ├── img-2.jpg
│ ├── img-3.jpg
│ ├── img-4.jpg
│ ├── logo.png
│ ├── user-1.jpg
│ ├── user-2.jpg
│ └── user-3.jpg
├── index.html
├── script.js
└── style.css
├── LICENSE
├── README.md
├── css
├── main.css
└── main.css.map
├── docs
├── README.md
├── assignments.pdf
└── coding-challenges.pdf
├── favicon.ico
├── index.html
├── package-lock.json
├── package.json
├── renovate.json
└── sass
└── main.scss
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | GOALS.md
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "markdown.experimental.validate.ignoreLinks": [
3 | "../02-Fundamentals-Part-2/assignment.js"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/00_introduction/README.md:
--------------------------------------------------------------------------------
1 | ## What is JavaScript?
2 |
3 | JavaScript is a High level, object oriented, multi-paradigm programming language.
4 |
5 | - A programming language is a tool that allows one to write code that will instruct a computer to do something.
6 | - JavaScript is a high level language, which means that we don't have to worry about a lot of stuff like managing a computer's memory while it runs. Which makes JavaScript easier to write and learn.
7 | - JavaScript is object oriented which means the language is mostly based on objects for storing data.
8 | - JavaScript is also a multi paradigm language meaning that it is so flexible and versartile that we can use all kinds of different programming styles. And this styles are just ways of structuring our code.
9 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/01_hello_world/Hello_world.js:
--------------------------------------------------------------------------------
1 | // You can write a basic "Hello World" program in JavaScript with the browser console
2 |
3 | // To do that, type the command below in your browser console
4 |
5 | alert("Hello World!");
6 |
7 | // This will popup an alert that says "Hello World"
8 |
9 | // More examples
10 |
11 | let js = "amazing";
12 | if (js === "amazing") alert("JavaScript is Fun!");
13 |
14 | // This will pop up an alert that says 'JavaScript is Fun'
15 | // In the code above, we took a variable (js) with a string of text 'amazing' and said:
16 |
17 | // if the variable (js) is 'amazing', which it true, alert the text 'JavaScript is Fun!'
18 |
19 | // If we change the string on the variable (js) and we try to run the program again, it won't work because the variable has being assigned to a different string. E.g
20 |
21 | js = "boring";
22 | if (js === "amazing") alert("JavaScript is Fun!");
23 |
24 | // This script is false because js is no longer amazing but has been changed to boring.
25 |
26 | // You can also do mathematical calculations in the console
27 |
28 | 20 + 30 + 20;
29 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/01_hello_world/README.md:
--------------------------------------------------------------------------------
1 | ## What do we use JavaScript for?
2 |
3 | Javascript is used to add dynamics and effects to a webpage. Manipulate content (HTML & CSS), load data from remote servers and to build entire applications in the browser, which we call web apps.
4 |
5 | ## There is nothing you can't do with JavaScript (Well, Almost)
6 |
7 | ### Frontend Applications
8 |
9 | Javascript is completely dynamic and is the language that the popular frameworks and libraries like React, Angular and Vue are built in. These libraries might go away but JavaScript won't so it's a good idea to have a good foundation of JavaScript itself.
10 |
11 | ### Backend Applications
12 |
13 | JavaScript can also run outside of web browsers. For e.g It is possible to use JavaScript on the web server using a very popular technology called NodeJS which doesn't need any browser at all and this allows us to create backend applications which are simply applications that run on a web server and to interact with databases, ETC.
14 |
15 | ### Native Mobile and Desktop Applications
16 |
17 | JavaScript has really changed the whole developement industry over the last couple of years, making things possible that has been really difficult. With the help of frameworks and libraries like Ionic, React Native, Electron, JavaScript can be used to build native mobile and desktop applications.
18 |
19 | ## JavaScript Releases
20 |
21 |
22 |
23 | There has been a huge update to the JavaScript language in 2015 which is oficially called ES2015 but porpularly called ES6, because it was the update that came after ES5. Also new releases has been introduced after the ES6 update which encapsulates everything we call Modern JavaScript.
24 |
25 | You can also use JavaScript to build native mobile applications as well as native desktop applications thanks to tools like React native, Ionic Framework and Electron.
26 |
27 | Now you understand how powerful JavaScript is and what it is used for, let's move on to other stuff.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/02_javascript_linking/README.md:
--------------------------------------------------------------------------------
1 | ## How to link a JavaScript File
2 |
3 | Usually when building frontend applications, JavaScript is attached to web pages in the HTML document.
4 |
5 | ### Inline Linking
6 |
7 | This involves writing JavaScript code inside the head of the HTML document. To do that, we can use the dedicated html tag which is the `` element.
8 |
9 | Now run the code in Hello_Js.
10 |
11 | ```js
12 |
15 | ```
16 |
17 | **Note**
18 | In JavaScript, you usually add a semi-colon(;) at the end of each line, this will let JavaScript know we are done with that line. Sometimes you might see people omit this semi-colon because it is not mandatory, but it is good practice to add it, plus it makes your code look neat.
19 |
20 | So we have added our code inside the script tag and now if we open up the `index.html` file, our JavaScript program should give us an alert that says.
21 |
22 | > JavaScript is FUN!
23 |
24 | You can also add the mathematical calculations in our code.
25 |
26 | ```js
27 |
31 | ```
32 |
33 | In order to execute the mathematical operation, we simply need to use a function: `console.log` to tell JavaScript to execute the operation to the console.
34 |
35 | ```js
36 |
40 | ```
41 |
42 | ### External linking
43 |
44 | Usually when writing code, you want to seperate the logic from the content. Which means our JavaScript code should be in a seperate JavaScript file.
45 |
46 | So create a new file for your JavaScript code and to link it to the html file, we can use the script tag to link it. ``
47 | This code is usually added to the bottom of the body tag.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/02_javascript_linking/script.js:
--------------------------------------------------------------------------------
1 | let js = "amazing";
2 |
3 | if (js === "amazing") alert("JavaScript is Fun!");
4 |
5 | 40 + 8 + 23 + 10;
6 | console.log(40 + 8 + 23 + 10);
7 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/03_values_variables/README.md:
--------------------------------------------------------------------------------
1 | ## Values and Variables
2 |
3 | A value is a piece of data which is the most fundamental unit of information in programming.
4 |
5 | **E.g:**
6 |
7 | `'Jonas', 'Eke'` are example of values.
8 | If we wrap it in a `console.log()` we should see it in the console.
9 |
10 | ```js
11 | console.log("Eke");
12 | ```
13 |
14 | You can have multiple values as well. For example the calculation we did earlier; `console.log(40 + 8 + 23 - 10)` had multiple numbers(values) which was combined with the math operators to give us one single value: `61`
15 |
16 | An extremely useful thing is to store data in variables so it can be reusable.
17 |
18 | ### What is a variable?
19 |
20 | Variables are containers for storing values.
21 | In JavaScript, you can store a value in a variable with the assignment operator `(=)`.
22 |
23 | **For example:**
24 |
25 | ```js
26 | let firstName = "Eke";
27 | ```
28 |
29 | In the code above, we have a container of `firstName` and this container holds or stores a value of `Eke` and now if we want to use this value, all we have to do is to use the variable name; `firstName` in this case.
30 |
31 | ```js
32 | let firstName = "Eke";
33 |
34 | console.log(firstName);
35 | ```
36 |
37 | Now in other to use the variable, we can do a `console.log()` and the variable name.
38 |
39 | ```js
40 | console.log(firstName);
41 | ```
42 |
43 | You can use this variable multiple times in your code, and anytime JavaScript sees the variable `firstName`, it'll replace it with the value we assigned to it.
44 |
45 | This is extremely useful because if you want to change the value of the variable, you only have to do it in one place.
46 |
47 | **For Example:**
48 | If we change the variable value from **Eke** to **John**, everywhere we referenced the variable will automatically get changed as well.
49 |
50 | ```js
51 | let firstName = "John";
52 |
53 | console.log(firstName);
54 | console.log(firstName);
55 | console.log(firstName);
56 | console.log(firstName);
57 | ```
58 |
59 | ### Variable Naming Conventions
60 |
61 | Now we have know what a variable is, we need to uderstand the rules and conventions for naming variables because we shouldn't use random names for variables.
62 |
63 | Variable names are called **identifiers** and can be short names (like x and y) or more descriptive (age, sum, firstName)
64 |
65 | #### Camel case
66 |
67 | This is a very popular naming convention in JavaScript, which involves writing the first word in lower case and all the next words in uppercase:
68 |
69 | **Like so:** `first`, `firstPerson`, `countNumber`. `selectMainUser`. Another popular one is using underscores: `first_name` count_number, ETC.
70 |
71 | ### Rules in naming variables
72 |
73 | There are also some strict rules in JavaScript on how you can name variables.
74 |
75 | - You can't start a variable name with a number.
76 |
77 | **Example:**
78 |
79 | ```js
80 | let 2boys = '3';
81 | ```
82 |
83 | Infact variables names can only contain numbers, letters, underscores and dollar sign.
84 |
85 | **Example**
86 |
87 | ```js
88 | let jonas&Matilda = 'name';
89 | ```
90 |
91 | This will prompt an error because **&** is not allowed to be used in variable names.
92 |
93 | - Another rule is to not start a variable name with an uppercase letter.
94 |
95 | **Example**
96 |
97 | ```js
98 | let Person = "Eke";
99 | ```
100 |
101 | Though this is not illegal to do, it is just that upper case letters are reserved for a specific use case in JavaScrit Object Oriented Programming.
102 |
103 | Starting a variable with uppercase are also reserved for constants that we know will never change.
104 |
105 | **Example:**
106 |
107 | ```js
108 | let PI = 3.14;
109 | ```
110 |
111 | We know the value of PI will never change, which makes it a constant and the convention for writing contants is using uppercase.
112 |
113 | - Writing descriptive variable names
114 | When writing JavaScript, it is good practice to write our variable names are descriptive. This helps the code to be more readable and will be easy to understand what the variable does just by reading the name.
115 |
116 | **For Example:**
117 | This variable name is more descriptive than
118 |
119 | ```js
120 | let myFirstJob = "Programmer";
121 | let myCurrentJob = "Teacher";
122 | ```
123 |
124 | Than writing this.
125 |
126 | ```js
127 | let job1 = "Programmer";
128 | let job2 = "Teacher";
129 | ```
130 |
131 | ```js
132 | console.log(myFirstJob);
133 | ```
134 |
135 | ### Reserved keywords
136 |
137 | You will also encounter errors in your javascript naming if you use reserved keywords like:
138 |
139 | - new
140 | - function
141 | - name, ETC.
142 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/03_values_variables/script.js:
--------------------------------------------------------------------------------
1 | let js = "amazing";
2 | console.log(40 + 8 + 23 - 10);
3 |
4 | // Function to run JavaScript code
5 | console.log("Eke");
6 | console.log("23");
7 |
8 | // Multiple variable
9 | let firstName = "Eke";
10 | console.log(firstName);
11 | console.log(firstName);
12 | console.log(firstName);
13 |
14 | let jonasMatilada = "3";
15 | let $function = "27";
16 |
17 | // Variables for naming constants
18 | let person = "Jonas";
19 | let PI = 3.1415;
20 |
21 | // Descriptive variables
22 | let myFirstJob = "Programmer";
23 | let myCurrentJob = "Teacher";
24 |
25 | // Undescriptive variables
26 | let job1 = "programmer";
27 | let job2 = "teacher";
28 |
29 | console.log(myFirstJob);
30 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/04_data_types/README.md:
--------------------------------------------------------------------------------
1 | ## Data Types
2 |
3 | In every programming language, values can have different types depending on the type of data we want them to hold. Earlier we looked at string and numbers but there are other data types.
4 |
5 | In JavaScript, every value is either an **object** or **primitive** data type.
6 |
7 |
8 |
9 | ### The 7 Primitive Data Types
10 |
11 | ### 1. Number:
12 |
13 | These are called floating point numbers, which means every number has a decimal point. For example the number **23** is actually seen as **23.0** Numbers are decimals and integer.
14 |
15 | ```js
16 | let js = 23;
17 | ```
18 |
19 | The value 23 is actually the same as saying 23.0 even though we didn't specify it.
20 |
21 | ### 2. String:
22 |
23 | Strings are sequence of characters used for texts. When using strings, always put them in quotes, wether single or double quotes and backtics **``**. If you don't, JavaScript will confuse it for variable names.
24 |
25 | ```js
26 | let firstName = "Eke";
27 | let lastName = `Tom Cruise!`;
28 | let hobby = "Programming and coding!";
29 | ```
30 |
31 | ### 3. Boolean
32 |
33 | Boolean are logical types that are used for providing two possibilities like: **true** or **false**, **yes** or **no**. So Booleans are mostly used in making decisions.
34 |
35 | ```js
36 | let fullAge = true;
37 | console.log(fullAge);
38 | ```
39 |
40 | Now on the console we would see fullAge value is set to true.
41 | In JavaScript, there is a logic you can use to show the type of value of a particular variable. This logic is called `typeof`
42 |
43 | ```js
44 | let fullAge = true;
45 | console.log(fullAge);
46 |
47 | console.log(typeof fullAge);
48 | ```
49 |
50 | Now when we check the console, we will see the data type of **fullAge**, which is a Boolean.
51 |
52 | These values types mentioned above are the 3 main value types you'll use the most, but there are still 4 more value types which might be a bit convincing.
53 |
54 | ### 4. Undefined:
55 |
56 | These are values taken by a variable name but is not yet defined('empty value'). In other words, these are variables that have been declared but haven't being assigned a value. For Example:
57 |
58 | ```js
59 | let children;
60 | console.log(children);
61 | ```
62 |
63 | As you can see the variable **children** has been declared but has not being assigned a value, in other words, undefined.
64 |
65 | If we use the `typeof` operator, we will get an undefined type in our console and an undefined `typeof`.
66 |
67 | ```js
68 | let children;
69 | console.log(children);
70 | console.log(typeof children);
71 | ```
72 |
73 | ### 5. Null:
74 |
75 | This also means 'Empty value', but is used in different circumstances, which we'll look at sometime later.
76 |
77 | ### 6. Symbol(ES2015)
78 |
79 | This data type simply means, value that is unique and cannot be changed. _(Not useful for now)_
80 |
81 | ### 7. BigInt (ES2020)
82 |
83 | These data types is used for large integers that the `number` data type can't hold. So it's basically another type for numbers.
84 |
85 | ### Dynamic Typing
86 |
87 | It's also good to know that JavaScript has a feature called dynamic typing which means when you create a new variable, you don't need to define the data type of the value of that variable. This is a feature unique to JavaScript as other languages will require you to determine the data type.
88 |
89 | This distinction between data type and the variable is pretty important because in JavaScript, it's the value that has the type, not the variable.
90 |
91 | Another important thing to note about dynamic types is that variables can be assigned a new value with a different data type without any problems.
92 | **For Example**
93 |
94 | Variable `X` can intially be a number and then later, a string.
95 |
96 | Just like we did before, we can re-assign a new value to a variable we created.
97 |
98 | ```js
99 | children = 20;
100 | console.log(typeof children);
101 | ```
102 |
103 | Now when we check our console, we can see the type of `null` we had earlier has been changed to `number` This is the power of dynamic typing in JavaScript.
104 |
105 | **Error/bug in typeof**
106 | When we use the `typeof` function to check the data type of an empty variable, the result in the console was **Undefined**, because we did not define the variable, now when we try to check the `typeof` of `null`, we get an error like so.
107 |
108 | ```js
109 | console.log(typeof null);
110 | ```
111 |
112 | The console sees the typeof as an **object** This is an error/bug that has not being fixed in JavaScript for legacy reasons. This is an error because `null` is not an object and should return `null` as `null` just like we had `undefined` return as `undefined`.
113 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/04_data_types/script.js:
--------------------------------------------------------------------------------
1 | // Declared a varible (Boolean)
2 | let javascriptIsFun = true;
3 | console.log(javascriptIsFun);
4 |
5 | console.log(typeof true);
6 | console.log(typeof javascriptIsFun);
7 | console.log(typeof 23);
8 | console.log(typeof "Eke");
9 |
10 | // Redefine the variable with a new value (string)
11 | javascriptIsFun = "YES!";
12 | console.log(typeof javascriptIsFun);
13 |
14 | // Undefined variable
15 | let year;
16 | console.log(year);
17 | console.log(typeof year);
18 |
19 | // Assign a value to (year)
20 | year = 1991;
21 | console.log(year);
22 | console.log(typeof year);
23 |
24 | // JavaScript typeof error
25 | console.log(typeof null);
26 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/05_let_const_var/README.md:
--------------------------------------------------------------------------------
1 | ## 9. Let, Const, Var
2 |
3 | There are basically 3 main ways of declaring a variable, which includes:
4 |
5 | - let
6 | - const
7 | - var
8 |
9 | `let` and `const` were both introduced in ES6 so they are modern JavaScript while the `var` keyword is the old way of declaring variables. Let's learn the differences and which one to use in which situation.
10 |
11 | ### When to Use JavaScript var?
12 |
13 | Always declare JavaScript variables with var, let, or const.
14 |
15 | - The var keyword is used in all JavaScript code from 1995 to 2015.
16 | - The let and const keywords were added to JavaScript in 2015.
17 | - Var supports older browsers.
18 |
19 | #### let
20 |
21 | - Use the `let` keyword to declare variables that can change later.
22 | **For example:**
23 |
24 | ```js
25 | let age = 24;
26 |
27 | age = 25;
28 | ```
29 |
30 | In the code above, we have a variable with a vlaue of 24 which was later changed to 25. This is known as re-assigning a variable or mutating a variable.
31 |
32 | So when we need to mutate a variable, `let` is the perfect use case. This also counts in declaring empty variables.
33 |
34 | Declaring empty variables can sometimes be useful in a case where we want to declare all the variables at the top of the file but only assign actual values to them later in the program based on some condition or issue.
35 |
36 | **For Example:**
37 |
38 | ```js
39 | let age;
40 |
41 | age = 32;
42 | ```
43 |
44 | Here we declared a variable without assigning it a value at first and then on the second line, we assigned that empty variable we declared, a value of `32`
45 |
46 | #### const
47 |
48 | The `const` meaning, Constant keyword is used to declare variables that are not supposed to change at any point in the future.
49 |
50 | **For Example:**
51 |
52 | ```js
53 | const PI = 3.14;
54 | ```
55 |
56 | In maths, we know that the value of `PI` is 3.14... so we use const to declare this variable because it is a constant that cannot be changed.
57 |
58 | If we try to use the `const` keyword to declare a muteable variable, it will give an error in our code. Like so:
59 |
60 | ```js
61 | const dateOfBirth = 1997;
62 |
63 | dateOfBirth = 1998;
64 | ```
65 |
66 | If we run this code, we will get an error because the const keywords cannot be mutated or reassigned a new value.
67 |
68 | Now the fact that variables created with the `const` keywords are immutable, also means that it can not ne used to assign empty variables.
69 |
70 | **For Example:**
71 |
72 | ```js
73 | const job;
74 | ```
75 |
76 | ### let or const
77 |
78 | Now having talked about the differences between the `let` and `const` keywords the question is, which one should we use and in what situation?
79 |
80 | It is best practice to use the `const` keyword by default and only use let when you are really sure that the variable needs to change at some point in the future.
81 |
82 | The reason that makes this a good practice is that we want to have as little variable mutations or changes as possible because changing variables introduces a potential to create bugs. 🪲
83 | So by default, always use `const` and if you think the variable will have to change in the future, use `let`
84 |
85 | ### var
86 |
87 | This was the old way of declaring variables before (ES6) was introduced in 2015. Even though it is not recommended to use the `var` keyword in this time, it is still good to understand how it works for legacy reasons because you may see this in older codebases or tutorials online.
88 |
89 | **For Example:**
90 |
91 | ```js
92 | var job = "programmer";
93 |
94 | job = "technical writer";
95 | console.log(job);
96 | ```
97 |
98 | If we run this code, the result will give us 'technical writer' because the `var` keywords accepts mutating of variables.
99 | Now the `var` keyword might look pretty similar to `let` on the surface but they are actually very different under the hood which we will dive deeper into in further sections.
100 |
101 | Now it is good to know that you can use a variable without using one of these keywords we have talked about.
102 |
103 | **For Example**
104 |
105 | ```js
106 | age = 30;
107 | console.log(age);
108 | ```
109 |
110 | If we run this code, it will give us the age value of 30. In as much as this works, it is a terrible idea and not a good practice. You should always declare your variables properly using the `let`, `const` or `var` keywords.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/05_let_const_var/script.js:
--------------------------------------------------------------------------------
1 | // Let Const Var
2 | let age = 30;
3 | age = 31;
4 |
5 | // Const is used for declaring variables that cannot be changed
6 | const birthYear = 1997;
7 | // birthYear = 1990;
8 |
9 | // const job;
10 |
11 | var job = "programmer";
12 | job = "clown";
13 |
14 | console.log(job);
15 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/06_basic_operators/README.md:
--------------------------------------------------------------------------------
1 | ## 10. Basic Operators
2 |
3 | An operator allows you to transfer or combine multiple values, and do many more work with values. There are many categories of operators, we have **Mathematical/arithimetic operators**, **comparison operators**, **logical operators**, **assignment operators** and many more.
4 |
5 | ### Arithimetic Operators
6 |
7 | We have already used the minus(-) and plus(+) operators, but we can do all mathematial operations like multilplication, division and so on.
8 |
9 | **For example**
10 |
11 | ```js
12 | const ageEke = 2037 - 1997;
13 | const ageSarah = 2037 - 2018;
14 | console.log(ageEke, ageSarah);
15 | ```
16 |
17 | The result will be the calculated sum of 2037 - 1997 and 2037 - 2018.
18 | Since we specified 2037 in two different places, it will be good to add it to a variable so we don't have to repeat ourselves.
19 |
20 | ```js
21 | const now = 2037;
22 | ```
23 |
24 | Now we can use it in our code like this;
25 |
26 | ```js
27 | const ageEke = now - 1997;
28 | const ageSarah = now - 2018;
29 | console.log(ageEke, ageSarah);
30 | ```
31 |
32 | We also have other arithimetic operators:
33 |
34 | ```js
35 | console.log(ageEke - 2, ageEke / 10, 2 ** 3);
36 | ```
37 |
38 | `2 ** 3` is an exponent which means 2 raised to power 3 which is `2x2x2 = 8`
39 |
40 | We can also use arthimetic operators to join strings or in other words concatenate strings.
41 |
42 | ```js
43 | const firstName = "Victor";
44 | const lastName = "Eke";
45 | console.log(firstName + lastName);
46 | ```
47 |
48 | This will combine both values and give use a full string `VictorEke`
49 | You can add space between these values by using an empty string.
50 |
51 | ```js
52 | console.log(firstName + " " + lastName);
53 | ```
54 |
55 | ### Typeof Operator
56 |
57 | We already looked at the typeof operator and how we can use it to know the data type of a variable.
58 |
59 | ```js
60 | let ageEke = 32;
61 | console.log(typeof ageEke);
62 | ```
63 |
64 | This will give us the data type of ageEke value which is a `number`
65 |
66 | ### Assignment Operator
67 |
68 | It is also good to note that the equals `(=)` symbol is an operator on it's own.
69 |
70 | ```js
71 | let x = 10 + 5;
72 | console.log(x);
73 | ```
74 |
75 | If we run this code in the console, the plus `(+)` operator will be executed before the equal to`(=)` which is based on a couple of rules about operator precedence that we'll be looking at later.
76 |
77 | There are other assignment operators:
78 |
79 | ```js
80 | let x = 10 + 5; // 15
81 | x += 10; // x = x + 10 = 25
82 | x *= 4; // x = x * 4 = 100
83 | x++; // x = x + 1
84 | console.log(x);
85 | ```
86 |
87 | - `x += 10` simply means: The value of x + 10 =
88 | and since the value of x is 15, x = `10 + 15 = 25`
89 | - `x *= 4` means: The value of x _ 10 = Which will give be the previous value of x multiplied by 4. `x = 25 _ 4 = 100`
90 | - This will also work on the division operator
91 | - `x++` simply means: Add 1 to the value of x = `x + 1 = 101`
92 | - `x--` is the opposite of ++.
93 |
94 | ### Comparison Operators
95 |
96 | We use this operator to produce `BOOLEAN` values.
97 |
98 | ```js
99 | console.log(ageEke > ageSarah);
100 | ```
101 |
102 | This comparison is simply saying is the age of Eke (`ageEke`) greater than the age of Sarah (`ageSarah`), if yes, the answer would be true and if not, it will be false.
103 |
104 | And the answer is true because Eke's age is 40 and Sarahs's age is 19.
105 |
106 | This will be very useful later when we start taking decisions based on certain conditions.
107 |
108 | There are more comparison operators:
109 |
110 | ```js
111 | console.log(ageSarah >= 18) >, <, >=, <=
112 | ```
113 |
114 | The greater than equal to `>=` simply means if Sarah is greater than 18 or equal to 18. Since Sarah is 19 years old, this statement would be true and if she is less than 18 or the value is increased to 20, the result would be false:
115 |
116 | ```js
117 | console.log(ageSarah >= 20);
118 | ```
119 |
120 | Usually when you using this in real world examples, we would probably store the calculation in a variable. For Example:
121 |
122 | ```js
123 | const fullAge = ageSarah >= 20;
124 | ```
125 |
126 | We can do all the previous calculations we did in one line and JavScript will execute the ages first and then compare them with the operator in the middle.
127 |
128 | ```js
129 | console.log(now - 1997 > now - 2018);
130 | ```
131 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/06_basic_operators/script.js:
--------------------------------------------------------------------------------
1 | // BASIC OPERATORS
2 |
3 | // Math Operations
4 | /*
5 | const dob = 2021;
6 |
7 | const ageEke = dob - 1997;
8 | const ageSarah = dob - 2010;
9 | console.log(ageEke, ageSarah);
10 |
11 | console.log(ageEke * 2, ageSarah / 10, 2 ** 3);
12 | // 2 ** 3 means 2 raised to the power of 3 = 2 * 2 * 2
13 |
14 | const firstName = "Victor";
15 | const lastName = "Eke";
16 | console.log(firstName + " " + lastName);
17 |
18 | // Typeof operators
19 | console.log(typeof firstName);
20 |
21 | // Assignment operators
22 | let x = 10 + 5; // 15
23 | x += 10; // x = x + 10 = 25
24 | x *= 4; //x = x * 4 = 100
25 | x++; // x = x + 1
26 | x--; // x = x - 1
27 | x--; // x = x - 1
28 | console.log(x);
29 |
30 | // Comparison operators
31 | console.log(ageEke > ageSarah); // >, <, >=, <=
32 | console.log(ageSarah >= 10);
33 |
34 | const isFullAge = ageSarah >= 10;
35 | console.log(dob - 1991 > dob - 2010);
36 |
37 | */
38 |
39 | // Maths Operators
40 | const now = 2037;
41 | const ageEke = now - 1997;
42 | const ageSarah = now - 2018;
43 | // log multiple items together.
44 | console.log(ageEke, ageSarah);
45 |
46 | console.log(ageEke * 2, ageEke / 10, 2 ** 3);
47 | // 2 ** 3 means 2 to the power of 3 = 2 * 2 *2
48 |
49 | // Arithimetic operator
50 |
51 | const firstName = "Victor";
52 | const lastName = "Eke";
53 | console.log(firstName + lastName);
54 |
55 | // Add space between strings
56 | console.log(firstName + " " + lastName);
57 |
58 | // Typeof Operator
59 | // let ageEke = 32;
60 | // console.log(typeof ageEke);
61 |
62 | // Equal operator: the equals symbol is an operator on it's own.
63 |
64 | // Assignment operators
65 | let x = 10 + 5; // x = 15
66 | x += 10; // x = x + 10 = 25
67 | x *= 4; // x = x * 4 = 100
68 | x++; // x = x + 1;
69 | x--; // x = x - 1;
70 | console.log(x);
71 |
72 | // Comparison operators
73 | console.log(ageEke > ageSarah);
74 | console.log(ageSarah >= 18);
75 | console.log(ageSarah <= 18);
76 |
77 | // Add the previous calculation to a variable.
78 | const fullAge = ageSarah >= 18;
79 |
80 | // We can do all the previous calculation in one line
81 | console.log(now - 1997 > now - 2018);
82 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/07_operator_precedence/README.md:
--------------------------------------------------------------------------------
1 | ## 11. Operator Precedence
2 |
3 | ```js
4 | const now = 2037;
5 | const ageEke = now - 1997;
6 | const ageSarah = now - 2018;
7 |
8 | console.log(now - 1997 > now - 2018);
9 | ```
10 |
11 | Operator precedence is a collection of rules in JavaScript that reflect conventions about which procedure to perform first in a given mathematical expression.
12 |
13 | Operators with higher precedence will be executed before the lower ones.
14 |
15 | Let's take a look at the precedence of different operators from **MDN**.
16 |
17 |
18 |
19 | **Image Credit:** MDN DOCS
20 |
21 | Now we can use this table to understand the precedence of the operators in the code above and how it was executed.
22 |
23 | On the table, subtraction `-` has a higher precedence than greater than `>` which is why the numbers were executed first before making the comparison.
24 |
25 | On the table, we can also see which operators are executed from left to right.
26 |
27 | **For Example**.
28 |
29 | ```js
30 | console.log(25 - 10 - 5);
31 | ```
32 |
33 | Since subtraction is executed from left to right, the result of this calculation would be `10`
34 |
35 | ```js
36 | let x, y; // Declare two variables in one line
37 | x = y = 25 - 10 - 5; // x = y = 10. y = 10, x = 10
38 | conslole.log(x, y);
39 | ```
40 |
41 | The result in the above example would be `10, 10`.
42 | This is because JavaScript will look at the calculation and run the ones with the higher precedence (in this case `-`) first before the assignment operator (`=`).
43 |
44 | ```js
45 | const averageAge = ageEke + ageSarah / 2;
46 | console.log(ageEke, ageSarah, averageAge);
47 | ```
48 |
49 | Here we are calculating the average value of `ageEke` & `ageSarah` and dividing it by `2`
50 |
51 | Result would be:
52 | **40 19 49.5**
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/07_operator_precedence/script.js:
--------------------------------------------------------------------------------
1 | const now = 2037;
2 | const ageEke = now - 1997;
3 | const ageSarah = now - 2018;
4 |
5 | console.log(now - 1997 > now - 2018);
6 |
7 | console.log(25 - 10 - 5);
8 |
9 | let x, y;
10 | x = y = 25 - 10 - 5; // x = y = 10. x = 10, y = 10
11 | console.log(x, y);
12 |
13 | const averageAge = ageEke + ageSarah / 2;
14 | console.log(ageEke, ageSarah, averageAge);
15 |
16 | /* Result would be
17 | 40 19 49.5
18 | */
19 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/08_coding_challenge_1/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## 🎉 Coding Challenge 1
3 |
4 | ```js
5 | Mark and John are trying to compare their BMI (Body Mass Index),
6 | which is calculated using the formula: BMI = mass / height ** 2 = mass / (height * height). (mass in kg and height in meter).
7 |
8 | 1. Store Mark's and John's mass and height in variables
9 | 2. Calculate both their BMIs using the formula (you can even implement both versions)
10 | 3. Create a boolean variable 'markHigherBMI' containing information about whether Mark has a higher BMI than John.
11 |
12 | TEST DATA 1: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.
13 | TEST DATA 2: Marks weights 95 kg and is 1.88 m tall. John weights 85 kg and is 1.76 m tall.
14 |
15 | GOOD LUCK 😀
16 | ```
17 |
18 | ## 🎉 Solution
19 |
20 | ```js
21 | // --------- TEST DATA 1 ------------
22 | const massMark = 78;
23 | const heightMark = 1.69;
24 |
25 | const massJohn = 92;
26 | const heightJohn = 1.95;
27 |
28 | const BMImark = massMark / heightMark ** 2;
29 | const BMIjohn = massJohn / (heightJohn * heightJohn);
30 |
31 | const markHigherBMIs = BMImark > BMIjohn;
32 | console.log(BMImark, BMIjohn, markHigherBMIs);
33 |
34 | // --------- TEST DATA 2 ------------
35 | const massMark = 95;
36 | const heightMark = 1.88;
37 | const massJohn = 85;
38 | const heightJohn = 1.76;
39 |
40 | const BMImark = massMark / heightMark ** 2;
41 | const BMIjohn = massJohn / (heightJohn * heightJohn);
42 |
43 | const markHigherBMI = BMImark > BMIjohn;
44 | console.log(BMImark, BMIjohn, markHigherBMI);
45 | ```
46 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/08_coding_challenge_1/script.js:
--------------------------------------------------------------------------------
1 | // Coding Challenge #1
2 |
3 | /*
4 | Mark and John are trying to compare their BMI (Body Mass Index), which is calculated using the formula: BMI = mass / height ** 2 = mass / (height * height). (mass in kg and height in meter).
5 |
6 | 1. Store Mark's and John's mass and height in variables
7 | 2. Calculate both their BMIs using the formula (you can even implement both versions)
8 | 3. Create a boolean variable 'markHigherBMI' containing information about whether Mark has a higher BMI than John.
9 |
10 | TEST DATA 1: Marks weights 78 kg and is 1.69 m tall. John weights 92 kg and is 1.95 m tall.
11 | TEST DATA 2: Marks weights 95 kg and is 1.88 m tall. John weights 85 kg and is 1.76 m tall.
12 |
13 | GOOD LUCK 😀
14 | */
15 |
16 | /*
17 | ======================================================
18 | ================== MY SOLUTION 🤩 ====================
19 | =======================================================
20 | */
21 |
22 | // ------------------- TEST DATA 1 ----------------------
23 |
24 | // Mark's Data
25 | const markMass = 78;
26 | const markHeight = 1.69;
27 |
28 | // John's Data
29 | const johnMass = 92;
30 | const johnHeight = 1.95;
31 |
32 | // Mark's BMI
33 | console.log(markMass / markHeight ** 2); // Mark BMI = 27.309968138370508
34 |
35 | // John's BMI
36 | console.log(johnMass / (johnHeight * johnHeight)); // John BMI = 24.194608809993426
37 |
38 | // markHigherBMI
39 | const johnBMI = 24.194608809993426;
40 | const markBMI = 27.309968138370508;
41 |
42 | const markHigherBMI = markBMI > johnBMI;
43 | console.log(markHigherBMI);
44 |
45 | // ------------------- TEST DATA 2 ----------------------
46 | // Mark's Data
47 | // const markMass = 95;
48 | // const markHeight = 1.88;
49 |
50 | // // John's Data
51 | // const johnMass = 85;
52 | // const johnHeight = 1.76;
53 |
54 | // // Mark's BMI
55 | // console.log(markMass / markHeight ** 2); // Mark BMI = 26.87867813490267
56 |
57 | // // John's BMI
58 | // console.log(johnMass / johnHeight ** 2); // John BMI = 27.44059917355372
59 |
60 | // // markHigherBMI
61 | // const markBMI = 26.87867813490267;
62 | // const johnBMI = 27.44059917355372;
63 |
64 | // const markHigherBMI = markBMI > johnBMI;
65 | // console.log(markHigherBMI);
66 |
67 | /*
68 | ======================================================
69 | ================== JONAS's SOLUTION 🤩 ====================
70 | =======================================================
71 | */
72 |
73 | // TEST 1
74 | // const massMark = 78;
75 | // const heightMark = 1.69;
76 | // const massJohn = 92;
77 | // const heightJohn = 1.95;
78 |
79 | // TEST 2
80 | const massMark = 95;
81 | const heightMark = 1.88;
82 | const massJohn = 85;
83 | const heightJohn = 1.76;
84 |
85 | const BMImark = massMark / heightMark ** 2;
86 | const BMIjohn = massJohn / (heightJohn * heightJohn);
87 |
88 | const markHigherBMIs = BMImark > BMIjohn;
89 | console.log(BMImark, BMIjohn, markHigherBMIs);
90 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/09_strings_template_literals/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## 12. Strings & Template Literals
3 |
4 | Strings are a very important part of programming and this section will understand what template literals is and how to build strings better and faster.
5 |
6 | Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
7 |
8 | ```js
9 | const firstName = "Eke";
10 | const job = "Software Developer";
11 | const birthYear = 1991;
12 | const year = 2021;
13 | ```
14 |
15 | Now let's concatenate these variables to build a string using quotes.
16 |
17 | ```js
18 | const eke = 'I'm '
19 | ```
20 |
21 | The above expression posses a challenge because when using words like I'm or Isn't (basically words that requires you to use single quotes), it won't work because the single quotes you're using with `'I'm` will finish the string.
22 |
23 | So in other to use the single quote, we'll have to switch to double quotes for outlining the strings.
24 |
25 | ```js
26 | const eke =
27 | "I'm " + firstName + ", a " + (year - birthYear) + " years old " + job + "!";
28 |
29 | console.log(eke);
30 | ```
31 |
32 | We can see this is a pain to write and we have to manage the spacing between each string and text. This brings us to our topic **"Template Literals:"** which is an easy way of writing strings in a normal way and then insert variables directly into the string.
33 |
34 | So basically a template literal can assemble multiple pieces in one final string.
35 |
36 | **Example:**
37 | To write a template literal, we use a backtick to assemble the strings. In other to add the variable, we'll add the variable in a curly braces and a dollar sign before it. `${variable}`
38 |
39 | ```js
40 | // Template literals
41 | const ekeNew = `I'm ${firstName}, a ${year - birthYear} years old ${job}!`;
42 | console.log(ekeNew);
43 | ```
44 |
45 | You can see this is easier and shorter to write. No need for adding the plus signs to concatenate the strings.
46 |
47 | We can also use the backticks for regular expressions of strings.
48 |
49 | ```js
50 | console.log(`This is Just a string...`);
51 | ```
52 |
53 | Many developers adopt this method of using backticks instead of single or double quotes when defining strings, this is a choice you can make, if you want.
54 |
55 | Another good use of template literals is to create multi lined strings. Before ES6, we needed to add a `\n\` to create a new line.
56 |
57 |
58 |
59 | ```js
60 | console.log(
61 | "String with \n\
62 | multiple \n\
63 | lines"
64 | );
65 | ```
66 |
67 |
68 |
69 | ```js
70 | console.log(`String with
71 | multiple
72 | lines`);
73 | ```
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/09_strings_template_literals/script.js:
--------------------------------------------------------------------------------
1 | // Template Literals
2 |
3 | const firstName = "Victor";
4 | const job = "Programmer";
5 | const birthYear = 1997;
6 | const year = 2022;
7 |
8 | const eke =
9 | "I'm " + firstName + ", a " + (year - birthYear) + " years old " + job + "!";
10 |
11 | console.log(eke);
12 |
13 | // Template literals
14 | const ekeNew = `I'm ${firstName}, a ${year - birthYear} years old ${job}!`;
15 | console.log(ekeNew);
16 |
17 | console.log(`This is Just a string...`);
18 |
19 | // Multi lined strings (ES5)
20 | console.log("String with \n\
21 | multiple \n\
22 | line");
23 |
24 | // Multi lined template string (ES6)
25 | console.log(`String with
26 | multiple
27 | lines`);
28 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/10_taking_decisions_if_else_statements/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## 13. Conditional Statements - if else
3 |
4 | Conditional statements are used to perform different actions based on different conditions.
5 |
6 | Very often when you write code, you want to perform different actions for different decisions.
7 |
8 | ### if statement
9 |
10 | The `if` statement is used to specify a block of JavaScript code to be executed when a condition is true.
11 |
12 | **For Example**
13 |
14 | ```js
15 | if (condition) {
16 | // condition is a boolean
17 | // Execute this code if condition is true.
18 | }
19 | ```
20 |
21 | Now let's write a program that checks if a person is allowed to start taking a drivers license or not. And if not, it will print how many years are left until the person can start taking their drivers license.
22 |
23 | ```js
24 | const age = 19;
25 | const requirement = age >= 18;
26 | if (requirement) {
27 | console.log("Sarah can have her driving license 🚗");
28 | }
29 | ```
30 |
31 | This will execute the command because the result is `true` because Sarah is 19 years old. But if we make Sarah 15 years the result will be false because the required age is 18.
32 |
33 | Now let's write an `else statement that will print when the result is false.
34 |
35 | ### else statement
36 |
37 | The else statement is basically a block of code to be executed if the condition is false.
38 |
39 | ```js
40 | if () {
41 |
42 | } else (condition) {
43 | // Execute this code if the condition is false.
44 | }
45 | ```
46 |
47 | ```js
48 | const age = 16;
49 |
50 | if (age >= 18) {
51 | console.log(`Sarah can start her driving license! 🚗`);
52 | } else {
53 | const requirement = 18 - age;
54 | console.log(
55 | `Sarah is too young. Wait another ${requirement} more year(s) 👶🏾`
56 | );
57 | }
58 | ```
59 |
60 | The Else block is not compulsory, if the condition of a code block is `false`, it will not output any code.
61 |
62 | Now the combination of the `if` and `else` statement is called a control structure. And this is reffered to as a structure because it allows us to have more control of the way the code is executed. For example, with the `if, else` statement, we specified the code blocks that should execute and the one that shouldn't, this gives us more control over how the code works.
63 |
64 | There are more control structures, but we'll be discussing more about that in the future.
65 |
66 | Let's see another example. In this example, we'll write a code that detects what century a person falls into using their year of birth.
67 |
68 | ```js
69 | const birthYear = 1997;
70 | let century;
71 |
72 | // Person was born below or at year 2000.
73 | if (birthYear <= 2000) {
74 | century = 20; // if true, execute 20th century
75 | } else {
76 | century = 21; // if false, execute 21st century
77 | }
78 |
79 | console.log(century);
80 | ```
81 |
82 | It is good to note that, any variable defined inside a code block will not be accessible outside of the code block.
83 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/10_taking_decisions_if_else_statements/script.js:
--------------------------------------------------------------------------------
1 | // Drivers license check
2 | const age = 19;
3 | const isOldEnough = 18;
4 |
5 | if (age >= 18) {
6 | console.log(`Sarah can start her drivers license. 🚗`);
7 | } else {
8 | const requirement = isOldEnough - age;
9 | console.log(`Sarah is too young. Wait ${requirement} more years. 👶🏾`);
10 | }
11 |
12 | // Century
13 | const birthYear = 1997;
14 | let century;
15 |
16 | if (birthYear <= 2000) {
17 | // Person was born below or at year 2000.
18 | century = 20; // if true, execute 20th century
19 | } else {
20 | century = 21; // if false, execute 21st century
21 | }
22 | console.log(century);
23 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/11_coding_challenge_2/README.md:
--------------------------------------------------------------------------------
1 | ## 🎉 Coding Challenge 2
2 |
3 | ```
4 | Use the BMI example from Challenege #1, and the code you already wrote, and improve it:
5 |
6 | 1. Print a nice output to the console, saying who has the higher BMI. The message can be either "Mark's BMI is higher than John's!" or "John's BMI is higher than Mark's!"
7 |
8 | 2. Use a template string to include the BMI values in the outputs. Example: "Mark's BMI (28.3) is higher than John's BMI (23.9)!"
9 |
10 | Hint: Use an if/else statement. 😉
11 |
12 | GOOD LUCK 🤩
13 | ```
14 |
15 | ## Solution
16 |
17 | ```js
18 | // TEST 1
19 | const massMark = 78;
20 | const heightMark = 1.69;
21 | const massJohn = 92;
22 | const heightJohn = 1.95;
23 |
24 | // TEST 2
25 | // const massMark = 95;
26 | // const heightMark = 1.88;
27 | // const massJohn = 85;
28 | // const heightJohn = 1.76;
29 |
30 | const johnBMI = massJohn / (heightJohn * heightJohn);
31 | const markBMI = massMark / (heightMark * heightMark);
32 |
33 | if (markBMI > johnBMI) {
34 | console.log(
35 | `Mark's BMI (${markBMI}) is higher than John's BMI (${johnBMI}) 💙`
36 | );
37 | } else {
38 | console.log(
39 | `John's BMI (${johnBMI}) is higher than Mark's BMI (${markBMI}) 💜`
40 | );
41 | }
42 | ```
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/11_coding_challenge_2/script.js:
--------------------------------------------------------------------------------
1 | // ! Coding challenege #2
2 |
3 | /*
4 | Use the BMI example from Challenege #1, and the code you already wrote, and improve it:
5 |
6 | 1. Print a nice output to the console, saying who has the higher BMI. The message can be either "Mark's BMI is higher than John's!" or "John's BMI is higher than Mark's!"
7 |
8 | 2. Use a template string to include the BMI values in the outputs. Example: "Mark's BMI (28.3) is higher than John's BMI (23.9)!"
9 |
10 | Hint: Use an if/else statement. 😉
11 |
12 | GOOD LUCK 🤩
13 | */
14 |
15 | // TEST 1
16 | const massMark = 78;
17 | const heightMark = 1.69;
18 | const massJohn = 92;
19 | const heightJohn = 1.95;
20 |
21 | // TEST 2
22 | // const massMark = 95;
23 | // const heightMark = 1.88;
24 | // const massJohn = 85;
25 | // const heightJohn = 1.76;
26 |
27 | const johnBMI = massJohn / (heightJohn * heightJohn);
28 | const markBMI = massMark / (heightMark * heightMark);
29 |
30 | if (markBMI > johnBMI) {
31 | console.log(
32 | `Mark's BMI (${markBMI}) is higher than John's BMI (${johnBMI}) 💙`
33 | );
34 | } else {
35 | console.log(
36 | `John's BMI (${johnBMI}) is higher than Mark's BMI (${markBMI}) 💜`
37 | );
38 | }
39 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/12_type_conversion_coercion/script.js:
--------------------------------------------------------------------------------
1 | // Type conversion and coercion
2 | const inputYear = "1991";
3 |
4 | console.log(inputYear);
5 | console.log(Number(inputYear), inputYear);
6 | console.log("number" - inputYear + 22); // Nan
7 | console.log(Number(inputYear) + 18); //
8 | console.log(Number("Eke")); // Nan
9 | console.log(typeof NaN); // Number
10 | console.log(String(23), 23);
11 |
12 | console.log("I am " + 13 + " years old"); // "I am 13 years old"
13 | console.log("I am " - 13 - " years old"); // NaN
14 | console.log("2" + 2 + "2" + 2); // 2222
15 | console.log("23" + "10" + 3); // "23103"
16 | console.log("23" - "10" - 3); // 10
17 | console.log("23" / "2"); // 11.5
18 | console.log("23" > "18"); // True
19 |
20 | // Guess the output
21 | let n = "1" + 1;
22 | n = n - 1;
23 | console.log(n); // 10
24 |
25 | console.log(2 + 3 + 4 + "5"); // "95"
26 | console.log("10" - "4" - "3" - 2 + "5"); // "15"
27 |
28 | console.log("I am " + Number(23) + " years old");
29 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/13_truthy_falsy_values/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Evavic44/Learn-JavaScript/927358ce7de6527b788948397986c6b32103a990/01-Fundamentals-Part-1/13_truthy_falsy_values/README.md
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/13_truthy_falsy_values/script.js:
--------------------------------------------------------------------------------
1 | console.log(Boolean(0)); // With the number 0 = false
2 | console.log(Boolean(undefined)); // With undefined = false
3 | console.log(Boolean("Eke")); // With a string = true
4 | console.log(Boolean("")); // With an empty string = false
5 | console.log(Boolean({})); // With an empty object = true
6 |
7 | // Type coercion in if/else condition
8 | const money = 0;
9 | if (money) {
10 | console.log("Don't have any money 💵");
11 | } else {
12 | console.log("You should get a job! 👷🏾");
13 | }
14 |
15 | // If a variable is defined or not
16 | let height;
17 | if (height) {
18 | console.log("Yay! Height is defined");
19 | } else {
20 | console.log("Height is UNDEFINED");
21 | }
22 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/14_equality_operators/README.md:
--------------------------------------------------------------------------------
1 | ## 15. Equality Operators
2 |
3 | So far we have only used comparions operators to take decisions in an if/else statement but instead of checking if a value is greater or lesser than the other, with equality operator, we can check if these values are exactly the same.
4 |
5 | To do that, we have different equality operators.
6 |
7 | ### Strict Equality Operator `===`
8 |
9 | This is a type of equality operator that doesn't perform type coercion and only returns true when both values are exactly the same.
10 |
11 | Example:
12 |
13 | ```js
14 | const age = 18;
15 |
16 | if (age === 18) console.log("You just became an adult! 😊");
17 | ```
18 |
19 | In this situation, we used a triple equals to check if the age is exactly 18. Now if we run this on the console, we can see it is true, because the age is exactly 18. But if the age is higher or lesser than 18, nothing will show on the console.
20 |
21 | ```js
22 | 18 === 18; // True
23 | "18" === 18; // False because `18` the string is not the same as 18 the number
24 | ```
25 |
26 | Now don't confuse the assignment which is just a single equal (=) with the comparison operator which is the (===) equal.
27 |
28 | ### Loose Equality Operator `==`
29 |
30 | This is the opposite of the strict equality which deals with double equals and it supports type coercion.
31 |
32 | For example, JavaScript will convert a string to a number in the loose equality operation.
33 |
34 | ```js
35 | "18" == 18; // True "18" the string is the same as 18 the number
36 | ```
37 |
38 | Using the **loose** equality operator can introduce a lot of bugs in our code, so as a general rule of writing clean code, avoid the **loose** equality operator as much as you can. When comparing values, always use **strict** equality operator with the === **equal** signs
39 |
40 | More Examples
41 |
42 | There is a pretty simple way of getting a value from any webpage using the prompt function.
43 |
44 | ```js
45 | prompt("What is your favourite number?");
46 | ```
47 |
48 | This will prompt an input field with the question or text "What is your favourite number?"
49 |
50 | In other to store the value someone enters into the input field, we need to store it in a variable.
51 |
52 | ```js
53 | const favNumber = prompt("What is your favourite Number?"); // Stores the inputed value
54 | console.log(favNumber); // Log to the conole.
55 | ```
56 |
57 | Now when we input a number, it will be stored in the console as a string. You can see that if we use the typeof function, it is a string
58 |
59 | ```js
60 | console.log(typeof favNumber); // Data type is a string
61 | ```
62 |
63 | Now let's write a logic here to check if the number inputted is the right number.
64 |
65 | ```js
66 | if (favNumber == 23) {
67 | // '23' == 23
68 | console.log("Cool! 23 is an amazing number!");
69 | }
70 | ```
71 |
72 | This worked because we used the **loose** equality operator which supports type coercion.
73 |
74 | However if we used the strict operator, this will not work unless because it doesn't support type coercion, unless we manually convert the strings to numbers.
75 |
76 | ```js
77 | const favNumber = Number(prompt("What's your favourite number?"));
78 |
79 | if (favNumber === 23) {
80 | // 23 === 23 True
81 | console.log("Cool! 23 is an amazing number!");
82 | }
83 | ```
84 |
85 | ### Else if statement
86 |
87 | We can also add more conditions to an `if/else` statement.
88 |
89 | ```js
90 | if (favNumber === 23) {
91 | console.log("Cool! 23 is an amazing number!");
92 | } else if (favNumber === 7) {
93 | console.log("7 is also a cool number!");
94 | } else if (favNumber === 100) {
95 | console.log("100 is also a cool Number!");
96 | } else {
97 | console.log("Number is not 23 or 7 or 100");
98 | }
99 | ```
100 |
101 | Now if we type in 7, the `else/if` block will be executed and the value will be **"7 is also a cool number"** and if we type in a value that is neither 23 nor 7, the `else` block will be executed to say **"Number is not 23 or 7"**
102 |
103 | All this statements worked with the strict `(===)` equality operator because we manually converted the string `favNumber` to a number.
104 |
105 | We can also keep adding more `else/if` block if we want. So we are not restricted to one option if a certain condition is true or false, it will go through other `else/if` statements before it gives us a result.
106 |
107 | So basically, it will check for 23, if it doesnt find it, it will move to 7 if it still doesn't find it, it will move to the next number until it reaches the final stage which is running the `else` block.
108 |
109 | ### Different operator
110 |
111 | The different operator is the opposite of the equality operator. It also have the `loosy` and `strict` type. The symbol for this operator is `!==` for the strict different operator and `!=` for the loose different operator.
112 |
113 | Example
114 |
115 | ```js
116 | if (favNumber !== 23) console.log("Why not 23?");
117 | ```
118 |
119 | Now if we input a value that is not 23, the result in the console will be "Why not 23?" because we have specified a condition if the value is not `23`. What if we use the 23, then we won't have any result on the console concerning the different operator block of code.
120 |
121 | Sometimes we need the equality operator and sometimes we need the different operator, just choose whatever you need to solve any particular problem. In both cases, make sure you always use the strict version of the operator.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/14_equality_operators/script.js:
--------------------------------------------------------------------------------
1 | const age = 18;
2 | if (age === 18) console.log("You just became an adult! (strict)");
3 | if (age == 18) console.log("You just became an adult! (loose)");
4 |
5 | // Strict equality operator
6 | console.log(18 === 18); // True because 18 is the same as 18
7 | console.log("18" === 18); // False because "18" the string is not the same as 18 the number in a strict equality operator
8 | console.log(18 === 19); // False because 18 is not the same as 19
9 |
10 | // Loose equality operator
11 | console.log(18 == 18); // True
12 | console.log("18" == 18); // True because "18" the string is the same as 18 the number in a loose equality operator
13 |
14 | // How to get a number from a webpage using prompt
15 | // prompt("What is your favourite Number? 🔢");
16 |
17 | // Store the value inputed.
18 | // Manually convert the strings to number
19 | const favNumber = Number(prompt("What is your favourite Number❓")); // Prompts the question
20 |
21 | console.log(favNumber); // Stores the inputed value
22 | console.log(typeof favNumber); // Log to the conole.
23 |
24 | // else if conditions
25 | if (favNumber === 23) {
26 | console.log("Cool! 23 is an amazing number!");
27 | } else if (favNumber === 7) {
28 | console.log("7 is also a cool Number!");
29 | } else if (favNumber === 100) {
30 | console.log("100 is also a cool Number!");
31 | } else {
32 | console.log("Number is not 23 or 7 or 100");
33 | }
34 |
35 | // Different operator
36 |
37 | if (favNumber !== 23) console.log("Why not 23?");
38 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/15_boolean_logic/script.js:
--------------------------------------------------------------------------------
1 | age = 16;
2 |
3 | /*
4 | A. Age is greater or equal 20 = false
5 | B. Age is less than 30 = true
6 |
7 |
8 |
9 | Using Operators!
10 |
11 | !A = true
12 | A AND B = false
13 | A OR B = true
14 | !A AND B = true
15 | A or !B = false
16 | */
17 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/16_logical_operators/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## 17 Logical Operators
3 |
4 | In the last lecture, we learned what Logical operators are, now let's jump into our code and learn how logical operators work in JavaScript.
5 |
6 | We'll be using the Boolean varaibles from the last lecture.
7 |
8 | **A**: Sarah has a driver's license
9 | **B**: Sarah has a good vision
10 |
11 | ```js
12 | const hasDriversLicense = true; // A
13 | const hasGoodVision = true; // B
14 |
15 | console.log(hasDriversLicense && hasGoodVision);
16 | ```
17 |
18 | We've created two variables that says, Sarah has a drivers license and has a good vision and set them both to true as the example from the last lecture.
19 |
20 | Now we combined both logical values using the `AND(&&)` operator in JavaScript.
21 |
22 | The result in the console is `true` because `hasDriversLicense` is true and `hasGoodVision` is also true, but if we change one of the values to `false`, the result will become `false` because in an `And` operation, it is enough for one variable to be false for the result of the operation to be false.
23 |
24 | Now let's see what it would look like with the `Or` operator.
25 |
26 | ```js
27 | console.log(hasDriversLicense || hasGoodVision);
28 | ```
29 |
30 | Combining the same values but this time with the `OR` operator. The result for this would be `true` because we know that it is enough for one of the variables to be `true`, for the whole operation to be `true`
31 |
32 | Finally, we can use the `Not` operator to invert values. In javaScript, the `Not` operator is the exclamation mark `(!)`.
33 |
34 | ```js
35 | console.log(!hasDriversLicense);
36 | ```
37 |
38 | So in the console `!hasDriversLicense` will become false because it will invert the values.
39 |
40 | Now we know how all of this works, we can use it to take a decision.
41 |
42 | ```js
43 | const shouldDrive = hasDriversLicense && hasGoodVision;
44 |
45 | if (shouldDrive) {
46 | console.log("Sarah is able to drive");
47 | } else {
48 | console.log("Someone else should drive...");
49 | }
50 |
51 | // Or you can just add the condition in the if() block
52 |
53 | if (hasDriversLicense && hasGoodVision)
54 | ```
55 |
56 | Our module is that in other for Sarah to drive, she has to have a drivers license and good vision.
57 |
58 | If she does, the result would be `true` and it'll execute the `if()` block, if not, it'll execute the `else()` block.
59 |
60 | So for our code above, the result is `true` and that is because `hasDriversLicense` is `true` and `hasGoodVision` is `true` and we know that if both conditions are `true` in an `And` operation, the result would be `true`. On the other hand, if one of the variables was false, the result also would be false.
61 |
62 | Let's look at another example.
63 | We can also look at the `OR` operator which is the `||` symbol in JavaScript.
64 |
65 | ```js
66 | const isTired = true; // C
67 |
68 | console.log(hasDriversLicense || hasGoodVision || isTired);
69 | ```
70 |
71 | The result of this would be true because all of the variables are true.
72 |
73 | Now we can use all of this to improve our decision making wether Sarah should drive or not.
74 |
75 | With this third variable, we want Sarah to be able to drive if:
76 |
77 | - She has a drivers License.
78 | - She has good vision
79 | - She is not tired.
80 |
81 | ```js
82 | if (hasDriversLicense && hasGoodVision && !isTired) {
83 | console.log("Sarah is able to drive!");
84 | } else {
85 | console.log("Someone else should drive");
86 | }
87 | ```
88 |
89 | The `else()` block would be executed because `isTired` is inverted and has become false because it is enough if one variable is false to make all of them false. To fix this, we need to change `isTired` to false and then Sarah can be able to drive.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/16_logical_operators/script.js:
--------------------------------------------------------------------------------
1 | const hasDriversLicense = true; // A
2 | const hasGoodVision = true; // B
3 |
4 | console.log(hasDriversLicense && hasGoodVision);
5 | console.log(hasDriversLicense || hasGoodVision);
6 | console.log(!hasDriversLicense);
7 |
8 | // if (hasDriversLicense && hasGoodVision) {
9 | // console.log("Sarah is able to drive");
10 | // } else {
11 | // console.log("Someone else should drive...");
12 | // }
13 |
14 | const isTired = false; // C
15 | console.log(hasDriversLicense && hasGoodVision && isTired);
16 |
17 | if (hasDriversLicense && hasGoodVision && !isTired) {
18 | console.log("Sarah is able to drive");
19 | } else {
20 | console.log("Someone else should drive...");
21 | }
22 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/17_coding_challenge_3/README.md:
--------------------------------------------------------------------------------
1 | ## 🎉 Coding Challenge 3
2 |
3 | ```js
4 | There are two gymnastics teams, Dolphins and Koalas.
5 | They compete against each other 3 times. The winner with the highest average score wins the a trophy!
6 |
7 | 1. Calculate the average score for each team, using the test data below.
8 |
9 | 2. Compare the team's average scores to determine the winner of the competition, and print it to the console. Don't forget that there can be a draw, so test for that as well (draw means they have the same average score).
10 |
11 | 3. BONUS 1: Include a requirement for a minimum score of 100. With this rule, a team only wins if it has a higher score than the other team, and the same time a score of at least 100 points. HINT: Use a logical operator to test for minimum score, as well as multiple else-if blocks 🙂
12 |
13 | 4. BONUS 2: Minimum score also applies to a draw! So a draw only happens when both teams have the same score and both have a score greater or equal 100 points. Otherwise, no team wins the trophy,
14 |
15 | TEST DATA
16 | Dolphins score 96, 108, 89.
17 | Koalas score 88, 91, 110
18 |
19 | TEST DATA BONUS 1:
20 | Dolphins score 97, 112 and 101.
21 | Koalas score 109, 95, 123
22 |
23 | TEST DATA BONUS 2:
24 | Dolphins score 97, 112 and 101.
25 | Koalas score 109, 95, and 106
26 |
27 | GOOD LUCK 🙂
28 | ```
29 |
30 | ## 🎉 Solution
31 |
32 | ```js
33 | // Main
34 | const scoreDolphins = (96 + 108 + 89) / 3;
35 | const scoreKoalas = (88 + 91 + 110) / 3;
36 | console.log(scoreDolphins, scoreKoalas);
37 |
38 | if (scoreDolphins > scoreKoalas) {
39 | console.log("Dolphins win the trophy 🏆");
40 | } else if (scoreKoalas > scoreDolphins) {
41 | console.log("Koalas win the trophy 🏆");
42 | } else if (scoreDolphins === scoreKoalas) {
43 | console.log("Both win the trophy!");
44 | }
45 |
46 | // Bonus 2 & 3
47 | const scoreDolphins = (97 + 112 + 101) / 3;
48 | const scoreKoalas = (109 + 95 + 106) / 3;
49 | console.log(scoreDolphins, scoreKoalas);
50 |
51 | if (scoreDolphins > scoreKoalas && scoreDolphins >= 100) {
52 | console.log("Dolphins win the trophy 🏆");
53 | } else if (scoreKoalas > scoreDolphins && scoreKoalas >= 100) {
54 | console.log("Koalas win the trophy 🏆");
55 | } else if (
56 | scoreDolphins === scoreKoalas &&
57 | scoreDolphins >= 100 &&
58 | scoreKoalas >= 100
59 | ) {
60 | console.log("Both win the trophy!");
61 | } else {
62 | console.log("No one wins the trophy 😭");
63 | }
64 | ```
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/17_coding_challenge_3/script.js:
--------------------------------------------------------------------------------
1 | /*
2 | There are two gymnastics teams, Dolphins and Koalas.
3 | They compete against each other 3 times. The team with the highest average score wins the trophy!
4 |
5 | 1. Calculate the average score for each team, using the test data below.
6 |
7 | 2. Compare the team's average scores to determine the winner of the competition, and print it to the console. Don't forget that there can be a draw, so test for that as well (draw means they have the same average score).
8 |
9 | 3. BONUS 1: Include a requirement for a minimum score of 100. With this rule, a team only wins if it has a higher score than the other team, and the same time a score of at least 100 points. HINT: Use a logical operator to test for minimum score, as well as multiple else-if blocks 🙂
10 |
11 | 4. BONUS 2: Minimum score also applies to a draw! So a draw only happens when both teams have the same score and both have a score greater or equal 100 points. Otherwise, no team wins the trophy,
12 |
13 | TEST DATA
14 | Dolphins score 96, 108, 89.
15 | Koalas score 88, 91, 110
16 |
17 | TEST DATA BONUS 1:
18 | Dolphins score 97, 112 and 101.
19 | Koalas score 109, 95, 123
20 |
21 | TEST DATA BONUS 2:
22 | Dolphins score 97, 112 and 101.
23 | Koalas score 109, 95, and 106
24 |
25 | GOOD LUCK 🙂
26 | */
27 |
28 | // =============== MY SOLUTION ========================
29 | // =============== MY SOLUTION ========================
30 |
31 | // Solution One 😁✅ // Got this right
32 | const dolphins = (96 + 108 + 89) / 3;
33 | const koalas = (88 + 91 + 110) / 3;
34 |
35 | console.log(dolphins, koalas);
36 |
37 | if (dolphins > koalas) {
38 | console.log("Dolphins won the competition! 🐬");
39 | } else if (dolphins < koalas) {
40 | console.log("Koalas won the competition! 🐨");
41 | } else if (dolphins === koalas) {
42 | console.log("The match is a draw! 🤝🏽");
43 | } else {
44 | console.log("Nobody Won!");
45 | }
46 |
47 | // Bonus 1 😭❌ // Got this wrong
48 | const dolphinsOne = (97 + 112 + 101) / 3;
49 | const koalasOne = (109 + 95 + 123) / 3;
50 | const hasMinimumScore = 100;
51 |
52 | console.log(dolphinsOne, koalasOne);
53 |
54 | if (dolphinsOne > koalasOne && hasMinimumScore) {
55 | console.log("Dolphins won the competition! 🐬");
56 | } else if (dolphinsOne < koalasOne && hasMinimumScore) {
57 | console.log("Koalas won the competition! 🐨");
58 | } else if (dolphinsOne === koalasOne) {
59 | console.log("The match is a draw! 🤝🏽");
60 | } else {
61 | console.log("Nobody Won!");
62 | }
63 |
64 | // Bonus 2 😭❌ // Got this wrong
65 | const dolphinsTwo = (97 + 112 + 101) / 3;
66 | const koalasTwo = (109 + 95 + 106) / 3;
67 | const score = 100;
68 |
69 | if (dolphinsTwo === koalasTwo) {
70 | console.log("Game is a draw", dolphinsTwo, koalasTwo);
71 | } else if (dolphinsTwo >= score) {
72 | console.log("Dolphins Won!");
73 | } else if (koalasTwo >= score) {
74 | console.log("Koalas Won!");
75 | }
76 |
77 | // =============== JONAS'S SOLUTION ========================
78 | // =============== JONAS'S SOLUTION ========================
79 |
80 | // const scoreDolphins = (96 + 108 + 89) / 3;
81 | // const scoreKoalas = (88 + 91 + 110) / 3;
82 | // console.log(scoreDolphins, scoreKoalas);
83 |
84 | // if (scoreDolphins > scoreKoalas) {
85 | // console.log("Dolphins win the trophy 🏆");
86 | // } else if (scoreKoalas > scoreDolphins) {
87 | // console.log("Koalas win the trophy 🏆");
88 | // } else if (scoreDolphins === scoreKoalas) {
89 | // console.log("Both win the trophy!");
90 | // }
91 |
92 | const scoreDolphins = (97 + 112 + 101) / 3;
93 | const scoreKoalas = (109 + 95 + 106) / 3;
94 | console.log(scoreDolphins, scoreKoalas);
95 |
96 | if (scoreDolphins > scoreKoalas && scoreDolphins >= 100) {
97 | console.log("Dolphins win the trophy 🏆");
98 | } else if (scoreKoalas > scoreDolphins && scoreKoalas >= 100) {
99 | console.log("Koalas win the trophy 🏆");
100 | } else if (
101 | scoreDolphins === scoreKoalas &&
102 | scoreDolphins >= 100 &&
103 | scoreKoalas >= 100
104 | ) {
105 | console.log("Both win the trophy!");
106 | } else {
107 | console.log("No one wins the trophy 😭");
108 | }
109 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/18_switch_statement/README.md:
--------------------------------------------------------------------------------
1 | ## 18 Switch Statement
2 |
3 | Switch statement is an alternative way of writing an if/else statement when all we want to do is to compare a value to multiple options.
4 |
5 | For example, let's say we have a weekday variable and for each, there is a different activity. Basically we're going to map one activity to each day.
6 |
7 | ```js
8 | const day = "monday";
9 |
10 | switch (day) {
11 | case "monday": // day === 'monday'
12 | console.log("Plan course structure");
13 | console.log("Go to coding meetup");
14 | break;
15 | case "tuesday": // if the day is eqaul to tuesday?
16 | console.log("Prepare theory videos"); // execute this code block
17 | break;
18 | case "wednesday":
19 | case "thursday":
20 | console.log("Write code examples");
21 | break;
22 | case "friday":
23 | console.log("Record videos");
24 | break;
25 | case "saturday":
26 | case "sunday":
27 | console.log("Enjoy the weekend");
28 | break;
29 | default:
30 | console.log("Not a valid day!");
31 | }
32 | ```
33 |
34 | In the code above, we're basically switching a variable of `day` and inside of the block, we'll have our code.
35 |
36 | Next we'll have a `case` which will take in the day of the week. Example: `"monday"`. Finally, underneath the case will be the code we want to execute.
37 |
38 | So basically, what the code will do is compare the day to monday in a strict equality way. So only if the day is monday, will the code be executed.
39 |
40 | ```js
41 | day === monday;
42 | ```
43 |
44 | #### Break
45 |
46 | The `break;` statement is used to tell the code to stop running after the break. So any code that comes after the break has been declared will not run, unless of course the day corresponds wihh the code.
47 |
48 | #### Default
49 |
50 | Default is like an else block at the end of a long if/else statement.
51 |
52 | The switch statement was designed for equality and not for like comparison operations.
53 | To get a better idea of how the switch statement work, we can convert it to an `if/esle` statement.
54 |
55 | ```js
56 | if (day === "monday") {
57 | console.log("Plan course structure 🎉");
58 | console.log("Go to coding meetup 🏆");
59 | } else if (day === "tuesday") {
60 | console.log("Prepare theory videos");
61 | } else if (day === "wednesday" || day === "thursday") {
62 | console.log("Write code examples");
63 | } else if (day === "friday") {
64 | console.log("Record videos");
65 | } else if (day === "saturday" || day === "sunday") {
66 | console.log("Enjoy the weekend");
67 | } else {
68 | console.log("Not a valid day!");
69 | }
70 | ```
71 |
72 | In this situation, the switch statement is a better solution because it looks more readable as compared to the `if/else` statement. Though the switch statement is becoming less and less used, but it is still worth learning because there are instances it could be helpful at times.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/18_switch_statement/script.js:
--------------------------------------------------------------------------------
1 | const day = "monday";
2 |
3 | switch (day) {
4 | case "monday": // day === 'monday'
5 | console.log("Plan course structure");
6 | console.log("Go to coding meetup");
7 | break;
8 | case "tuesday":
9 | console.log("Prepare theory videos");
10 | break;
11 | case "wednesday":
12 | case "thursday":
13 | console.log("Write code examples");
14 | break;
15 | case "friday":
16 | console.log("Record videos");
17 | break;
18 | case "saturday":
19 | case "sunday":
20 | console.log("Enjoy the weekend");
21 | break;
22 | default:
23 | console.log("Not a valid day!");
24 | }
25 |
26 | if (day === "monday") {
27 | console.log("Plan course structure 🎉");
28 | console.log("Go to coding meetup 🏆");
29 | } else if (day === "tuesday") {
30 | console.log("Prepare theory videos");
31 | } else if (day === "wednesday" || day === "thursday") {
32 | console.log("Write code examples");
33 | } else if (day === "friday") {
34 | console.log("Record videos");
35 | } else if (day === "saturday" || day === "sunday") {
36 | console.log("Enjoy the weekend");
37 | } else {
38 | console.log("Not a valid day!");
39 | }
40 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/19_statements_expressions/README.md:
--------------------------------------------------------------------------------
1 | ## 19. Statements & Expressions
2 |
3 | Let's take a high level overview of the difference between statements and expressions. Esentially, an expression is piece of code that produces a value.
4 |
5 | For example:
6 |
7 | ```js
8 | 3 + 4; // This is an expression
9 | 1991; // Also an expression
10 | true && false && !false;
11 | ```
12 |
13 | The examples above are all expressions because in JavaScript, they will all produce a value.
14 |
15 | Statements on the other hand is a like a bigger piece of code that is executed and does not produce a value by itself. We can compare this with normal spoken language. In this example, a decleration is like a complete sentence and expressions are like words that make up the sentences.
16 |
17 | Basically we write our whole programs as a sequence of actions and these actions are statements. For example, take the `if/else` statement.
18 |
19 | ```js
20 | if (23 > 10) {
21 | const str = "23 is bigger";
22 | }
23 | ```
24 |
25 | This `if/else` statement is infact a statement, and the same is true for the `switch` statement. The above example statement doesn't really produce a value, all it does is simply to declare the variable `str`. It performs some actions but it doesn't produce a value.
26 |
27 | This statement above is different from
28 |
29 | ```js
30 | 3 + 4;
31 | ```
32 |
33 | On the other hand, the string `"23 is bigger"` is an expression, and this might be a bit confusing but later in the course you'll understand it better. The aim of this section is not to learn the rules of these examples but to understand that expression produces values and statements are like full sentences that translate an action/program.
34 |
35 | Note:
36 |
37 | > Whenever something ends with a semi-colon, that is a statement. (Like a complete sentence).
38 |
39 | The difference between statements and expressions are important to know because JavaScript inserts statements and expressions in differenct places.
40 |
41 | For example, in a template literal, you can only insert expresions but not statements. To demonstare that:
42 |
43 | ```js
44 | console.log(`I'm ${2037 - 1991} years old`); // This is an expression.
45 | ```
46 |
47 | The code above worked because we added an expression. Let's say we add a statement, in that case, the code won't work.
48 |
49 | ```js
50 | console.logconsole.log(`I'm ${2037 - 1991} years old ${if (23 > 10) {
51 | const str = "23 is bigger";
52 | }}`);
53 | ```
54 |
55 | You can see we get an error because the above code we added is a statement, and this doesn't make sense because JavaScript expects an expression.
56 | But if we have a variable, for example:
57 |
58 | ```js
59 | const me = "Eke";
60 | console.log(`I'm ${2037 - 1991} years old`);
61 | ```
62 |
63 | This will also be an expression because the variable `me` will be replaced with the string `"Eke"` which produces a value and will work when we run it.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/19_statements_expressions/script.js:
--------------------------------------------------------------------------------
1 | 3 + 4;
2 | 1991;
3 | true && false && !true;
4 |
5 | if (23 > 10) {
6 | const str = "23 is bigger";
7 | }
8 |
9 | const me = "Eke";
10 | console.log(`I'm ${2037 - 1991} years old. ${me}`);
11 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/20_conditional_ternary_operator/README.md:
--------------------------------------------------------------------------------
1 | ## 20. Conditional (Ternary) Operator
2 |
3 | We've already seen two ways of writing conditionals, the `if/else` statement and the `switch` statement. Now, we'll look at another one called the `conditional operator`.
4 |
5 | The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.
6 |
7 | Source: [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)
8 |
9 | For example, let's define our age variable and write a piece of code to check if a person is old enough to do something or not.
10 |
11 | ```js
12 | const age = 23;
13 |
14 | age >= 18
15 | ? console.log("I like to drink wine 🍷")
16 | : console.log("I like to drink water 💦");
17 | ```
18 |
19 | When we execute the code above, of course it'll be true because the age is up to 18, which will execute the if statement. We can see this whole condition was done in one line.
20 |
21 | The conditional operator is actually an "operator" as the name says, and remember an operator always produces a value. In other words, an operator is an expression. What this means is that if we have a value, we can then assign that value to a variable.
22 |
23 | With this, we can make the ternary operator really useful to conditionally declare variables.
24 |
25 | Instead of writing the above example, we can do it like this.
26 |
27 | ```js
28 | age >= 18 ? "wine 🍷" : "water 💦";
29 | ```
30 |
31 | We can see that this whole operator is an expression, and expressions produces a value. Now we can store that value into a variable like this and print it to the console.
32 |
33 | ```js
34 | const drink = age >= 18 ? "wine 🍷" : "water 💦";
35 |
36 | console.log(drink);
37 | ```
38 |
39 | We can see that drink is defined conditionally all in one simple line. Without this conditional operator, we would have used the `if/else` statement which wouldn't be so easy. Remember when we want to declare a varaible inside of an `if/else` block, we need to declare that variable outside.
40 |
41 | ```js
42 | let drink2;
43 |
44 | if (age >= 18) {
45 | drink2 = "wine 🍷";
46 | } else {
47 | drink2 = "water 💦";
48 | }
49 |
50 | console.log(drink2);
51 | ```
52 |
53 | Again, we need to define the "drink2" variable outside of the `if/else` blocks. So we declared the varaible outside first, then we reassigned it inside the blocks.
54 |
55 | Now we really just did this for the sake of comparison, so you can see the tremendous difference that the ternary operator introduces in the code. In this example, the ternary operator is a lot easier to understand and write.
56 |
57 | Using the ternary operator, we were able to transform the big `if/else` block of code into one small operation.
58 |
59 | To take it a step further, since the ternary operator is an expression, we can also use it in a template literal, unlike using an `if/else` statement that we tried and failed in the previous lecture.
60 |
61 | ```js
62 | console.log(`I like to drink ${age >= 18 ? "wine 🍷" : "water 💦"}`);
63 | ```
64 |
65 | Finally, the ternary operator is not thought as a replacement of `if/else` statement. We still need if/else for bigger blocks of code that we need to execute based on a condition. In that case, the ternary is not going to work. So the ternary is perfect for simple expressions.
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/20_conditional_ternary_operator/script.js:
--------------------------------------------------------------------------------
1 | const age = 23;
2 | age >= 18
3 | ? console.log("I like to drink wine 🍷")
4 | : console.log("I like to drink water 💦");
5 |
6 | // Ternary expression
7 | const drink = age >= 18 ? "wine 🍷" : "water 💦";
8 | console.log(drink);
9 |
10 | let drink2;
11 | if (age >= 18) {
12 | drink2 = "wine 🍷";
13 | } else {
14 | drink2 = "water 💦";
15 | }
16 |
17 | console.log(drink2);
18 |
19 | // Conditional in template literal
20 | console.log(`I like to drink ${age >= 18 ? "wine 🍷" : "water 💦"}`);
21 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/21_coding_challenge_4/README.md:
--------------------------------------------------------------------------------
1 | ## Coding Challenge 4 🎉
2 |
3 | ```js
4 | Steven wants to build a very simple tip calculator for whenever he goes eating in a restaurant, In his country, it's usual to tip 15% if the bill value is between 50 and 300. If the value is different, the tip is 20%.
5 |
6 | 1. Your task is to calculate the tip, depending on the bill value. Create a variable called "tip" for this. It's not allowed to use an if/else statement 😿 (If it's easier for you, you can start with an if/else statement and then try to convert it to a ternary operator!)
7 |
8 | 2. Print a string to the console containing the bill value, the tip, and the final value (bill + tip). Example: "The bill was 275, the tip was 41.25, and the total value 316.25"
9 |
10 | TEST DATA: Test for bill values 275, 40, 430
11 | ```
12 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/21_coding_challenge_4/script.js:
--------------------------------------------------------------------------------
1 | /* Steven wants to build a very simple tip calculator for whenever he goes eating in a restaurant, In his country, it's usual to tip 15% if the bill value is between 50 and 300. If the value is different, the tip is 20%.
2 |
3 | 1. Your task is to calculate the tip, depending on the bill value. Create a variable called "tip" for this. It's not allowed to use an if/else statement 😿 (If it's easier for you, you can start with an if/else statement and then try to convert it to a ternary operator!)
4 |
5 | 2. Print a string to the console containing the bill value, the tip, and the final value (bill + tip). Example: "The bill was 275, the tip was 41.25, and the total value 316.25"
6 |
7 | TEST DATA: Test for bill values 275, 40, 430 */
8 |
9 | // Sudo Code
10 | // Tip 15% if bill === 50 && 300 (275)
11 | // Tip 20% otherwise === 40 (430)
12 |
13 | // If/else Example
14 | const bill = 257;
15 | const bill2 = 430;
16 | let tip;
17 |
18 | if (bill2 >= 50 && bill2 <= 300) {
19 | tip = (15 / 100) * bill2;
20 | } else {
21 | tip = (20 / 100) * bill2;
22 | }
23 |
24 | console.log(tip);
25 | console.log(
26 | `The bill was ${bill}, the tip was ${tip}, and the total value ${bill + tip}`
27 | );
28 |
29 | // Conversion to Ternary Operator
30 | const billValue =
31 | bill >= 50 && bill <= 300
32 | ? (tip = (15 / 100) * bill)
33 | : (tip = (20 / 100) * bill);
34 |
35 | console.log(billValue);
36 | console.log(
37 | `The bill was ${bill}, the tip was ${tip}, and the total value ${bill + tip}`
38 | );
39 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/22_javascript_releases_ES5_ES6+_ESNext/README.md:
--------------------------------------------------------------------------------
1 | ## 22. JavaScript Releases (ES5, ES6+ and ESNext)
2 |
3 | Now that you are familiar with the fundamentals of the JavaScript language, we need to talk about it's releases or versions before moving on. We brifely talked about it in the intro video, but not let's go into more depth because it's important to know about how JavaScript releases work and how we use them.
4 |
5 | ### A Brief History of JavaScript
6 |
7 | After the internet was invented, and the first web browsers were developed, developers wanted to make websites more interactive. In other words, they needed a programming language for the browser.
8 |
9 | ### 1995
10 |
11 | In 1995, the [Netscape Navigator](https://isp.netscape.com/) which by the time was the dominant browser, hired [Brandon Eich](https://twitter.com/brendaneich) to create the very first version of JavaScript in just 10 days. It was called **Mocha** at the time, and it already had many of the fundamental features modern JavaScript had today.
12 |
13 | ### 1996
14 |
15 | In 1996, Mocha was renamed to LiveScript and then to JavaScript to attract Java developers, However, **The Java in JavaScript has absolutely nothing to do with Java.** I was renamed for marketing reasons.
16 |
17 | ### 1996
18 |
19 | Microsoft launched the Internet Explorer(IE) which basically copied JavaScript from Netscape. But they called it JScript for legal reasons.
20 | The issue with this was we now had two very similar but competing languages.
21 |
22 | The internet grew rapidly in that time and so people realized that they needed to standardize JavaScript. Therefore, the language was submitted to an independet organization called [Ecma](https://www.ecma-international.org/).
23 |
24 | ### 1997
25 |
26 | In 1997, Ecma released ECMAScript 1 or ES1. This was the first official standard for JavaScript, and with this, everyone could now implement the same standard of JavaScript.
27 |
28 | ### 2009
29 |
30 | ES5 (ECMAScript 5) was released with a lot of great new features.
31 |
32 | ### 2015
33 |
34 | ES6/ES2015 (ECMAScript 2015) was releaesd: The biggest update to the language ever! It contained a ton of new exciting features which we will explore throughout this course.
35 |
36 | ES6 is also called ES2015 because ECMAScripr changed to an annual release cycle in order to ship less feature per update. This was because they preffered to just add a small number of features each year instead of shipping a huge new feature every couple of years like they did with ES6, and so this way, it will be much easier for everyone to keep up to date.
37 |
38 | ### 2016 - ♾️ Release of ES2016/ES2017/ES2018/.../ES2098
39 |
40 | ECMAScript will keep releasing new features in JavaScript every year until the end of time.
41 |
42 | ### Backwards Compatibility
43 |
44 |
45 |
46 | JavaScript is backwards-compatible. This means that once something is accepted as valid JS, there will not be a future change to the language that causes that code to become invalid JS. JS code written in 1995 - however primitive or limited - should still work now.
47 |
48 | The idea is that JS developers can write code with confidence that their code wouldn’t stop working unpredictably because a browser update is released.
49 |
50 | ### Forwards Compatibility
51 |
52 | JS is not forwards-compatible. This means that including a new addition to the language in a program would cause that program to break if it were run in an older JS engine. So if you run a program that uses an ES2019 feature in an engine from 2016, the program will very likely break and crash.
53 |
54 | ### How to use Modern JavaScript Today?
55 |
56 | We need to understand how we can use Modern JavaScript today, and to answer this question, we need to consider two scenarios. Development and production.
57 |
58 | - During Development: Simply use the latest Google Chrome
59 | - During Production: Use Babel to transpile and polyfill your code (converting back to ES5 to ensure browser compatibility for all users.)
60 |
61 | We need to understand that the users may not be using the latest browsers so in other to fix that, we need to basically convert this modern JavaScript versions back to ES5 using a process called Transpiling or Polyfilling.
62 |
63 | #### Babel (Transpiler)
64 |
65 | Typically forwards-compatibility problems related to syntax are solved by using a transpiler to convert from a newer JS syntax to an equivalent older version. The most common transpiler being used is Babel, which is mainly used to convert ECMASCRIPT-2015+ code into backwards compatible version of JavaScript in current and older browsers or environments.
66 |
67 | ### Compatibility Table
68 |
69 | This table helps you keep up-to date on JavaScript releases and what browsers these feature can work on.
70 |
71 |
72 |
--------------------------------------------------------------------------------
/01-Fundamentals-Part-1/assignment.js:
--------------------------------------------------------------------------------
1 | // Values & Variables
2 | const country = "Nigeria";
3 | const continent = "Africa";
4 | let population = 206100000;
5 |
6 | console.log(country, continent, population);
7 |
8 | // Data Types
9 | const isIsland = true;
10 | let language;
11 |
12 | console.log(
13 | typeof isIsland,
14 | typeof population,
15 | typeof country,
16 | typeof language
17 | );
18 |
19 | // Let, Const, & Var
20 | language = "English";
21 |
22 | // Basic Operators
23 | const halfPopulation = population / 2;
24 | console.log(halfPopulation);
25 | population++;
26 | console.log(population);
27 |
28 | const finland = 6000000;
29 | const isMore = population > finland;
30 | console.log(isMore);
31 |
32 | const isAverage = population < 33000000;
33 | console.log(isAverage);
34 |
35 | let description =
36 | "Nigeria is in \n Africa, and its 203 million \n people speak English";
37 |
38 | console.log(description);
39 |
40 | // Strings & Template Literals
41 | description = `${country} is in
42 | ${continent} and it's ${population}
43 | people speak ${language}`;
44 |
45 | console.log(description);
46 |
47 | // Taking Decision: If/Else Statements
48 | if (population > 33000000) {
49 | console.log(`${country}'s population is above average`);
50 | } else {
51 | console.log(
52 | `${country}'s population is ${population - 33000000} million below average`
53 | );
54 | }
55 |
56 | // Type Conversion and Coercion
57 | console.log("9" - "5"); // 4
58 | console.log("19" - "13" + "17"); // 617
59 | console.log("19" - "13" + 17); // 23
60 | console.log("123" < 57); // false
61 | console.log(5 + 6 + "4" + 9 - 4 - 2); // 1143
62 |
63 | // Equality Operators == vs ===
64 | // const numNeighbours = prompt(
65 | // "How many neighbour countries does your country have?"
66 | // );
67 |
68 | // if (Number(numNeighbours) === 1) {
69 | // console.log("Only 1 borders");
70 | // } else if (numNeighbours > 1) {
71 | // console.log("More than 1 borders");
72 | // } else {
73 | // console.log("No Borders");
74 | // }
75 |
76 | // Logical Operators
77 | if (language === "English" && population < 50000000 && !isIsland) {
78 | console.log(`You should live in ${country} 🙂`);
79 | } else {
80 | console.log(`${country} does not meet your criteria 😔`);
81 | }
82 |
83 | // The Switch Statement
84 | switch (language) {
85 | case "Chinese":
86 | case "Mandarin":
87 | console.log("MOST number of native speakers!");
88 | break;
89 | case "Spanish":
90 | console.log("Second place in number of native speakers!");
91 | break;
92 | case "English":
93 | console.log("Third Place");
94 | break;
95 | case "Hindi":
96 | console.log("Number Four");
97 | break;
98 | case "Arabic":
99 | console.log("Fifth most spoken language");
100 | break;
101 | default:
102 | console.log("Great language too. :D");
103 | }
104 |
105 | // The Conditional (Ternary) Operator
106 | console.log(
107 | `${country}'s population is ${population > 33 ? "above" : "below"} average`
108 | );
109 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/00_strict_mode/README.md:
--------------------------------------------------------------------------------
1 | ## What is Strict Mode
2 |
3 | **Strict** mode is a special mode in JavaScript that we can activate to write secure JavaScript code easily.
4 |
5 | ## How to Enable Strict Mode
6 |
7 | Enabling the strict mode is super easy, in other to do that, simply write the following string at the top of your script.
8 |
9 | ```js
10 | "Use strict";
11 | ```
12 |
13 | What is important is to remember that this string should be written at the very first line of your code. If you add any code before this command, the strict mode will not be activated. Though comments are allowed because JavaScript will simply ignore them.
14 |
15 | Also, the strict mode can be added to a specific `function` or code block. But there isn't any point in doing that. So stick to adding it on the first line.
16 |
17 | ## Importance and Examples
18 |
19 | Strict mode makes it eaiser for JavaScript developers to avoid certain errors in our code, and that is because of two reasons.
20 |
21 | - Strict mode forbids us to do certain things
22 | - Strict mode creates visible errors in the developer console where in other situations, JavaScript will just fail silently.
23 |
24 | ### Example
25 |
26 | In the code example below, we intentionally omitted the `"s"` in the `hasDriversLicense` variable. So what we have now is "hasDriverLicense". This is a very common mistake when writing code. When we run the code below, we don't get any results or warning, but if we enable the strict mode, JavaScript now warns us that `hasDriverLicense` variable is not defined.
27 |
28 | ```js
29 | // "use strict";
30 |
31 | let hasDriversLicense = false;
32 | const passTest = true;
33 |
34 | if (passTest) hasDriverLicense = true;
35 | if (hasDriversLicense) console.log("I can drive :D");
36 | ```
37 |
38 | Another thing that strict mode does is to introduce a shortlist of
39 | variable names that are reserved for features that might be added to the language later.
40 |
41 | ### Example
42 |
43 | let's create a variable called interface and give it a string value of "Audio"
44 |
45 | ```js
46 | const interface = "Audio";
47 | ```
48 |
49 | We can see JavaScript throws an error that `interface` is a reserved identifier, thanks to enabling the Strict mode.
50 | There are other reserved identifier, some we have already looked at in section 1 when we learned about Naming conventions in JavaScript.
51 |
52 | ```js
53 | const private = "444";
54 | const interface = "444";
55 | const function = "test";
56 | const if = "test";
57 | ```
58 |
59 | ## Reserved Keywords in JavaScript
60 |
61 | ```js
62 | private
63 | interface
64 | function
65 | if
66 | else
67 | ```
68 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/00_strict_mode/script.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | let hasDriversLicense = false;
4 | const passTest = true;
5 |
6 | if (passTest) hasDriversLicense = true;
7 | if (hasDriversLicense) console.log("I can drive :D");
8 |
9 | // Strict mode detecting reserved keywords in JavaScript.
10 | // const interface = "Audio";
11 | // const private = "444";
12 | // const function = "test";
13 | // const if = "test";
14 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/01_functions/script.js:
--------------------------------------------------------------------------------
1 | function logger() {
2 | console.log("My name is Eke");
3 | }
4 |
5 | // Calling / Running / invoking function
6 |
7 | logger();
8 | logger();
9 | logger();
10 |
11 | function furitProcessor(apples, oranges) {
12 | const juice = `Juice with ${apples} apples and ${oranges} oranges`;
13 |
14 | return juice;
15 | }
16 |
17 | // furitProcessor(5, 0);
18 |
19 | // Store the argument in a varaible
20 | const appleJuice = furitProcessor(5, 0);
21 | console.log(appleJuice);
22 |
23 | // Or log it to the console directly
24 | console.log(furitProcessor(5, 0));
25 |
26 | // Second argument
27 | const appleOrangeJuice = furitProcessor(2, 4);
28 | console.log(appleOrangeJuice);
29 |
30 | const num = Number("23");
31 | console.log(num);
32 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/02_functions_declarations_expressions/README.md:
--------------------------------------------------------------------------------
1 | In JavaScript, there are different ways of writing functions and each type of function works in a slightly different way.
2 |
3 | ## Function Declaration
4 |
5 | The function in the previous lecture is called "function declarations" because we simply used the function keyword to declare a function much like declaring a variable
6 |
7 | Let's now write a function declaration this time to calculate an age at a given birth year.
8 |
9 | ```js
10 | function calcAgeOne(birthYear) {
11 | // const age = 2022 - birthYear
12 | return 2022 - birthYear;
13 | }
14 | ```
15 |
16 | We can actually simplify this and return the code in one go. So instead of storing the return keyword in a variable `const age = 2022 - birthYear`, we can simply return the result of this expression. `return 2022 - birthYear`.
17 |
18 | And once again, this is a generic function that will work for any birth year that we give it. So now let's call/invoke/execute this function.
19 |
20 | ```js
21 | const ageOne = calcAgeOne(1997);
22 | console.log(ageOne);
23 | ```
24 |
25 | ## Function Expression
26 |
27 | Instead of writing a function with a name, we simply do it without a name, but we still define the parameter, the body and then store the whole function as a variable. This type of function is also called an anonymous function.
28 |
29 | For example:
30 |
31 | ```js
32 | const calcAgeTwo = function (birthYear) {
33 | return 2022 - birthYear;
34 | };
35 | ```
36 |
37 | So all of these is an expression and remember that an expression produces a value and we stored that value in a varaible, `calcAgeTwo`. Therefore, this variable now becomes the function. Now to call this function is the same way.
38 |
39 | ```js
40 | const ageTwo = calcAgeTwo(1997);
41 | console.log(ageTwo);
42 | ```
43 |
44 | The function expression works exactly the same way as the function declaration, we called it the same way, we captured it the same way, and the result is actually the same because the function body is the same. It is important to know that we have these two types of functions in JavaScript because in some places, we will need to write functions in different ways.
45 |
46 | It is also good to note that functions in JavaScript are just values, it is not a string or a number but a value and since it's a value, we can store it into a variable.
47 |
48 | So finally, what's the big difference between function declarations and function expressions?
49 |
50 | The main practical difference is that we can actually call function declarations before they are defined in the code.
51 |
52 | For Example:
53 |
54 | ```js
55 | const ageOne = calcAgeOne(1997)
56 |
57 | function calcAgeTwo = function(birthYear) {
58 | return 2022 - birthYear;
59 | }
60 | ```
61 |
62 | We defined the function before the declaration and it still worked, but if we try to do that with the expression, it'll give an error because of a process called `Hoisting` in JavaScript. More on that a little later.
63 |
64 | ## Conclusion
65 |
66 | So keep in mind that you can call a function declaration before you define it even though that might not be such a good idea in many cases. So which function should you use why writing your code? It's all about personal preference but it's good you understand how both works because both have their place in JavaScript.
67 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/02_functions_declarations_expressions/script.js:
--------------------------------------------------------------------------------
1 | // Function declaration
2 | function calcAgeOne(birthYear) {
3 | return 2022 - birthYear;
4 | }
5 |
6 | const ageOne = calcAgeOne(1997);
7 | console.log(ageOne);
8 |
9 | // Function Expression
10 | const calcAgeTwo = function (birthYear) {
11 | return 2022 - birthYear;
12 | };
13 |
14 | const ageTwo = calcAgeTwo(1997);
15 | console.log(ageTwo, ageOne);
16 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/03_arrow_function/README.md:
--------------------------------------------------------------------------------
1 | ## Arrow Function
2 |
3 | So we learned about function declarations and expressions in the last lecture but there is actually a third type of function that was added to JavaScript in ES6.
4 |
5 | Arrow function is simply a special form of function expression that is shorter and therefore faster to write.
6 |
7 | For Example
8 |
9 | ```js
10 | (birthYear) => 2022 - birthYear;
11 | ```
12 |
13 | First we write the parameter `birthYear`, followed by an arrow `=>` (which is why this is called an arrow function) and then simply write what we want to return `2022 - birthYear`. To run this, we need to store it into a variable just like we did in the previous lecture.
14 |
15 | ```js
16 | const calcAgeThree = (birthYear) => 2022 - birthYear;
17 | ```
18 |
19 | This is a special form of function expression because it is still an expression, and that is because all of `(birthYear) => 2022 - birthYear` will produce a value. You can see that it is basically similar to the Function Expression but Arrow function is much easier to write.
20 |
21 | The difference between arrow function and other ways of writing functions is that
22 |
23 | - We don't need the curly braces like we have previously in the code block
24 | - The `return` happens implicitly. The value will automatically be returned without us having to explicitly use the `return` keyword. So this is excellent for simple one-liner functions and very important in JavaScript.
25 |
26 | To call this function, it works exactly the same way as all the other functions. And again to use it, we need to store it inside a variable, and then log it to the console.
27 |
28 | ```js
29 | const ageThree = calcAgeThree(1997);
30 | console.log(ageThree);
31 | ```
32 |
33 | This is actually the simplest form, when we have only one parameter and only basically one line of code which we want to run something. Though it gets a bit more complex when we add more parameters or code.
34 |
35 | Example
36 | Let's calculate how many years a person has till retirement.
37 | We'll call this function `yearsUntilRetirement` and then we set that equal to a function. To calculate the retirement age, we first need to calculate the age and then from there, the retirement age - the current age, so we need more lines of code which brings us back to using the curly braces.
38 |
39 | First we calculate the current age.
40 | `const age = 2022 - birthYear;`
41 |
42 | And then calculate the years before retirement (let's say the retirement age is 65)
43 |
44 | `const retirement = 65 - age;`
45 |
46 | Now we actually need to wrtie the return keyword explicitly. We can only ommit the return when it is a one-liner function.
47 |
48 | ```js
49 | const yearsUntilRetirement = (birthYear) => {
50 | const age = 2022 - birthYear;
51 | const retirement = 65 - age;
52 | return retirement;
53 | };
54 |
55 | console.log(yearsUntilRetirement(1997));
56 | ```
57 |
58 | So that is the scenario when we have one parameter and more than one line of code. But what if we had multiple parameters, then we need to wrap the parameters into parenthesis and then return a string.
59 |
60 | We can use template strings like "First name retires in X years."
61 |
62 | ```js
63 | const yearsUntilRetirement = (birthYear, firstName) => {
64 | const age = 2022 - birthYear;
65 | const retirement = 65 - age;
66 | return `${firstName} retires in ${retirement} years`;
67 | };
68 |
69 | console.log(yearsUntilRetirement(1997, "Eke"));
70 | console.log(yearsUntilRetirement(1993, "John"));
71 | ```
72 |
73 | Now when we run this in the console, we get:
74 |
75 | - Eke retires in 40 years
76 | - John retires in 36 years
77 |
78 | So that is essentially how the arrow function works. You just need to keep in mind the couple of different scenarions that there are regarding the number of code or/and parameters.
79 |
80 | As you add more code and more parameters, it becomes more complex and we kind of lose the advantage of using an arrow function.
81 |
82 | ## What function should I use?
83 |
84 | Now we understand the different functions, it might be a bit confusing to decide which one to use. Should you use the arrow function which is easier to write everytime? The answer is No, and a bit complicated, because there is another fundamental difference between arrow functions and more traditional functions.
85 |
86 | The differnce is that Arrow functions does not get the `This` keyword. Which is a topic for later.
87 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/03_arrow_function/script.js:
--------------------------------------------------------------------------------
1 | // Arrow Function
2 | const calcAgeThree = (birthYear) => 2022 - birthYear;
3 |
4 | const ageThree = calcAgeThree(1997);
5 | console.log(ageThree);
6 |
7 | // const yearsTillRetirement = (birthYear) => {
8 | // const age = 2022 - birthYear;
9 | // const retirement = 65 - age;
10 |
11 | // return retirement;
12 | // };
13 |
14 | // console.log(yearsTillRetirement(1997));
15 |
16 | const yearsTillRetirement = (birthYear, firstName) => {
17 | const age = 2022 - birthYear;
18 | const retirement = 65 - age;
19 |
20 | return `${firstName} retires in ${retirement} years`;
21 | };
22 |
23 | console.log(yearsTillRetirement(1997, "Eke"));
24 | console.log(yearsTillRetirement(1993, "John"));
25 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/04_functions_calling_other_functions/README.md:
--------------------------------------------------------------------------------
1 | ## Functions calling other functions
2 |
3 | Functions calling other functions is something that we do all the time in JavaScript. To illustrate this, we'll use the `fruitProcessor` function we used earlier.
4 |
5 | ```js
6 | function fruitProcessor(apples, oranges) {
7 | const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
8 | return juice;
9 | }
10 | ```
11 |
12 | Remember this function was like a fruit processor that received a certain number of apples and oranges, and based on that, it produced and returned a juice. Now in this example, let's assume the fruit processor can only make juice with smaller fruit pieces.
13 |
14 | So before making a juice, the fruit processor now needs another machine to first cut the fruit that we give it into multiple smaller pieces. So let's write that function(machine) that cuts the fruit in multiple pieces.
15 |
16 | ```js
17 | function cutPieces(fruit) {
18 | return fruit * 4;
19 | }
20 | ```
21 |
22 | So we have our new function which will receive a `(fruit)` and return a fruit cut into 4 pieces. So if we get 2 apples, it will return 8 pieces to us.
23 |
24 | To use this machine, we'll start by calling fruitPieces in our `fruitProcessor` function with the number of apples we will receive, and the result of calling this function we will capture in a variable called `applePieces`. We'll also do the same for the oranges.
25 |
26 | ```js
27 | function fruitProcessor(apples, oranges) {
28 | const applePieces = cutPieces(apples);
29 | const orangePieces = cutPieces(oranges);
30 |
31 | const juice = `Juice with ${applePieces} pieces of apple and ${orangePieces} pieces of oranges.`;
32 | return juice;
33 | }
34 |
35 | console.log(fruitProcessor(2, 3));
36 | ```
37 |
38 | And the result is 8 pieces of apples and 12 pieces of oranges.
39 |
40 | Finally, with time and practice, you will exactly know when you should create your own functions, and when to have multiple functions one after another.
41 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/04_functions_calling_other_functions/script.js:
--------------------------------------------------------------------------------
1 | function cutFruitPieces(fruit) {
2 | return fruit * 4;
3 | }
4 |
5 | function fruitProcessor(apples, oranges) {
6 | const applePieces = cutFruitPieces(apples);
7 | const orangePieces = cutFruitPieces(oranges);
8 |
9 | const juice = `Juice with ${applePieces} pieces of apples and ${orangePieces} pieces of oranges`;
10 | return juice;
11 | }
12 |
13 | console.log(fruitProcessor(2, 4));
14 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/05_reviewing_functions/script.js:
--------------------------------------------------------------------------------
1 | const calcAge = function(birthYear) {
2 | return 2037 - birthYear;
3 | }
4 |
5 | const yearsUntilRetirement = function (birthYear, firstName) {
6 | const age = calcAge(birthYear);
7 | const retirement = 65 - age;
8 |
9 | if(retirement > 0) {
10 | console.log(`${firstName} retires in ${retirement} years`);
11 | return retirement;
12 | } else {
13 | console.log(`${firstName} has already retired 🎉`);
14 | return -1;
15 | }
16 | }
17 |
18 | console.log(yearsUntilRetirement(1997, "Eke"));
19 | console.log(yearsUntilRetirement(1950, "Mike"));
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/06_coding_challenge/README.md:
--------------------------------------------------------------------------------
1 | ## Coding Challenge
2 |
3 | Back to the two gymnastics teams, the Dolphins and the Koalas! There is a new gymnastics discipline, which works differently.
4 | Each team competes 3 times, and then the average of the 3 scores is calculated(so one average score per team).
5 |
6 | A team ONLY wins if it has at least DOUBLE the average score of the other team. Otherwise, no team wins!
7 |
8 | 1. Create an arrow function `calcAverage` to calculate the average of 3 scores.
9 | 2. Use the function to calculate the average for both teams.
10 | 3. Create a function `checkWinner` that takes the average score of each team as arguments(`avgDolphins` and `avgKoalas`), and then logs the winner to the console, together with the victory points, according to the rule above. Example: "Koalas win (30 vs. 13)".
11 | 4. Use the `checkWinner` function to determine the winner of both Data 1 and Data 2.
12 | 5. Ignore draws this time.
13 |
14 | ```js
15 | TEST DATA 1.
16 | Dolphins score 44, 23, and 71. Koalas score 65, 54, and 49.
17 | ```
18 |
19 | ```js
20 | TEST DATA 2.
21 | Dolphins score 85, 54, and 41. Koalas score 23, 34, and 27.
22 | ```
23 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/06_coding_challenge/script.js:
--------------------------------------------------------------------------------
1 | const calcAverage = (scoreOne, scoreTwo, scoreThree) =>
2 | (scoreOne + scoreTwo + scoreThree) / 3;
3 |
4 | // Test Data 1 Average
5 | let avgDolphins = calcAverage(44, 23, 71);
6 | let avgKoalas = calcAverage(65, 54, 49);
7 |
8 | // Test Data 2 Average
9 | avgDolphins = calcAverage(85, 54, 41);
10 | avgKoalas = calcAverage(23, 34, 27);
11 |
12 | console.log(avgDolphins, avgKoalas);
13 |
14 | const checkWinner = function (avgDolphins, avgKoalas) {
15 | if (avgDolphins >= avgKoalas * 2) {
16 | return `Dolphins win (${avgDolphins} vs ${avgKoalas}) 🏆`;
17 | } else if (avgKoalas >= avgDolphins * 2) {
18 | return `Koalas win (${avgKoalas} vs ${avgDolphins}) 🏆`;
19 | } else {
20 | return `No team wins! ❌`;
21 | }
22 | };
23 |
24 | console.log(checkWinner(avgDolphins, avgKoalas));
25 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/07_introduction_to_arrays/script.js:
--------------------------------------------------------------------------------
1 | // Introduction to Arrays
2 |
3 | const friend1 = "Michael";
4 | const friend2 = "Steven";
5 | const friend3 = "Peter";
6 |
7 | const friends = ["Michael", "Steven", "Peter"];
8 | console.log(friends);
9 |
10 | let years = new Array(1991, 1984, 2008, 2020);
11 |
12 | console.log(friends[0]);
13 | console.log(friends[1]);
14 | console.log(friends[2]);
15 | console.log(friends.length);
16 | console.log(friends[friends.length - 1]);
17 |
18 | friends[2] = "Jay";
19 | console.log(friends);
20 |
21 | // ["Michael", "Steven", "Peter"];
22 |
23 | // friends = ["Bob", "Alice"];
24 |
25 | const firstName = "Victor";
26 | const eke = [firstName, "Eke", 2022 - 1997, "Software Engineer"];
27 | console.log(eke);
28 | console.log(eke.length);
29 |
30 | const example = ["Name", "Age", friends];
31 | console.log(example);
32 | console.log(example.length);
33 |
34 | const calcAge = function (birthYear) {
35 | return 2022 - birthYear;
36 | };
37 |
38 | years = [1990, 1967, 2022, 2010, 2018];
39 |
40 | calcAge(years);
41 |
42 | const ageOne = calcAge(years[0]);
43 | const ageTwo = calcAge(years[1]);
44 | const ageThree = calcAge(years[years.length - 1]);
45 | console.log(ageOne, ageTwo, ageThree);
46 |
47 | const ages = [
48 | calcAge(years[0]),
49 | calcAge(years[1]),
50 | calcAge(years[years.length - 1]),
51 | ];
52 | console.log(ages);
53 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/08_basic_array_operations/README.md:
--------------------------------------------------------------------------------
1 | ## Basic Array Operations (Methods)
2 |
3 | JavaScript has some built-in function that we can basically apply on arrays, and these are called methods. Methods are simply array operations.
4 |
5 | There are countless array methods in JavaScript. We have a whole section dedicated to arrays alone. That is how important they are in JavaScript. In this section, we're going to be looking at the very crucial ones that we need to know.
6 |
7 |
8 |
9 | ## Push Method
10 |
11 | The `.push()` method is an array method that adds an element to the end of an array.
12 |
13 | ```js
14 | const friends = ["Michael", "Steven", "Peter"];
15 | friends.push("Jay");
16 |
17 | console.log(friends);
18 | ```
19 |
20 | ### Result
21 |
22 | ```js
23 | ["Michael", "Steven", "Peter", "Jay"];
24 | ```
25 |
26 | Push is essentially a function that is attached to the friends array. using the `dot`. We will explain why this happens in this way later on.
27 | When we check this in the console, we can see that `"Jay"` is now added to the end of the array, and the total count of the array is now changed to 4.
28 |
29 | Now, since `push` is a function, it can also return something. We can store the push function in a variable and run this variable to get the total number of values in the array.
30 |
31 | ```js
32 | const newLength = friends.push("Jay");
33 | console.log(newLength);
34 | ```
35 |
36 | ### Result
37 |
38 | ```js
39 | ["Michael", "Steven", "Peter", "Jay", "Jay"];
40 | ```
41 |
42 | ## Unshift Method
43 |
44 | The `.unshift()` method is an array metohd that adds an element to the beginning of an array.
45 |
46 | ```js
47 | friends.unshift("John");
48 | console.log(friends);
49 | ```
50 |
51 | ### Result
52 |
53 | ```js
54 | ["John", "Michael", "Steven", "Peter", "Jay", "Jay"];
55 | ```
56 |
57 |
58 |
59 | ## Pop Method
60 |
61 | Removes the last element in an array. It is basically the opposite of the push element.
62 |
63 | ```js
64 | friends.push;
65 | console.log(friends);
66 | ```
67 |
68 | The `pop()` method doesn't require passing any arguments, and that is because there is no information needed to really remove the last element.
69 |
70 | ```js
71 | friends.pop();
72 | friends.pop();
73 | ```
74 |
75 | ### Result
76 |
77 | ```js
78 | ["John", "Michael", "Steven"];
79 | ```
80 |
81 | The pop method also returns something, this time it returns a removed element which can sometimes be useful.
82 |
83 | ```js
84 | const popped = friends.pop();
85 | console.log(popped);
86 | ```
87 |
88 | ## Shift Method
89 |
90 | The shift method removes the first element in an array.
91 |
92 | ```js
93 | friends.shift();
94 | console.log(friends);
95 | ```
96 |
97 | ### Result
98 |
99 | ```js
100 | ["Michael", "Steven"];
101 | ```
102 |
103 | ## indexOf method
104 |
105 | This method tells us where an element is at in an array.
106 |
107 | ```js
108 | console.log(indexOf("Steven"));
109 | ```
110 |
111 | If we try this method with an element that is not present in the array, it will return -1.
112 |
113 | ```js
114 | console.log(indexOf("Bob"));
115 | ```
116 |
117 | ## includes() Method
118 |
119 | Similar to the `indexOf` method, the `includes()` method is used to check if an element is in an array and the result is a boolean value: True if the element is in the array, and false if it is not. The `includes()` method is an ES6 feature.
120 |
121 | ```js
122 | console.log(friends.includes("Steven"));
123 | console.log(friends.includes("Bob"));
124 | ```
125 |
126 | The `includes()` method uses the strict equality for this check. So if we push a number to this array and checked for `"23"` string using the `includes()` method, it'll return false because this method doesn't do type coercion.
127 |
128 | ```js
129 | friends.push(23);
130 | console.log(friends.includes("23"));
131 | ```
132 |
133 | But if we added the number directly and checked this number, it will return true.
134 |
135 | ```js
136 | friends.push(23);
137 | console.log(friends.includes(23));
138 | ```
139 |
140 | One of the useuful applicaitons of the `includes()` method is that it can be used to write conditionals.
141 |
142 | ```js
143 | if (friends.includes("Steven")) {
144 | console.log("You have a friend called Steven");
145 | }
146 | ```
147 |
148 | This of course will check the array for the string `"Steven"`, and if it is found, the result will be true, which will return the if statement.`
149 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/08_basic_array_operations/script.js:
--------------------------------------------------------------------------------
1 | // ARRAY METHOD
2 | const friends = ["Michael", "Steven", "Peter"];
3 | console.log(friends);
4 |
5 | // [Length] Sets or returns the number of elements in an array
6 | console.log(friends.length);
7 |
8 | // [Push] - Add elements to the end of an array
9 | friends.push("Jay");
10 | console.log(friends);
11 |
12 | // [Unshift] - Add elements to the beginning of an array
13 | friends.unshift("John");
14 | console.log(friends);
15 |
16 | // [Pop] - Removes last element of the array
17 | friends.pop();
18 | const popped = friends.pop();
19 | console.log(popped);
20 |
21 | // [Shift] - Removes first element of the array
22 | friends.shift();
23 | console.log(friends);
24 |
25 | // [IndexOf] - Tells us the position of an element in the array.
26 | console.log(friends.indexOf("Michael"));
27 |
28 | // Returns -1 if we check an element that is not in the array.
29 | console.log(friends.indexOf("Bob"));
30 |
31 | // Includes() - Check if an array contains the specified element using strict equality.
32 | friends.push(23);
33 | console.log(friends.includes("23"));
34 |
35 | // Conditionals with includes()
36 | if (friends.includes("Steven")) {
37 | console.log("You have a friend called Steven");
38 | }
39 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/09_coding_challenge/README.md:
--------------------------------------------------------------------------------
1 | ## Coding Challenge
2 |
3 | Steven is still building his tip calculator, using the same rules as before: Tip 15% of the bill if the bill value is between 50 and 300, and if the value is different, the tip is 20%.
4 |
5 | 1. Write a function 'calcTip' that takes any bill value as an input and returns the corresponding tip, calculated based on the rules above (you can check out the code from the first tip calculator challenge if you need to). Use the function type you like the most. Test the function using a bill value of 100.
6 |
7 | 2. And now let's use arrays! So create an array 'bills' containing the test data below.
8 |
9 | 3. Create an array 'tips' containing the tip value for each bill, calculated from the function you created before.
10 |
11 | 4. BONUS: Create an array 'total' containing the total values, so the bill + tip.
12 |
13 | ```js
14 | TEST DATA
15 |
16 | 125, 555 and 44
17 | ```
18 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/09_coding_challenge/script.js:
--------------------------------------------------------------------------------
1 | // Solution
2 | let tip;
3 | const calcTip = function (bill) {
4 | return bill >= 50 && bill <= 300
5 | ? (tip = (15 / 100) * bill)
6 | : (tip = (20 / 100) * bill);
7 | };
8 |
9 | // 1
10 | const testTip = calcTip(100);
11 | console.log(testTip);
12 |
13 | // 2
14 | const bills = [125, 555, 44];
15 | console.log(bills);
16 |
17 | // 3
18 | const tips = [calcTip(bills[0]), calcTip(bills[1]), calcTip(bills[2])];
19 | console.log(tips);
20 |
21 | // 4
22 | const total = [bills[0] + tips[0], bills[1] + tips[1], bills[2] + tips[2]];
23 | console.log(total);
24 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/10_introduction_to_objects/README.md:
--------------------------------------------------------------------------------
1 | ## Introduction to Object
2 |
3 | A JavaScript object is a collection of named values
4 |
5 | After arrays, objects are another type of data structure. Usually in arrays, we have different values combined into one entity.
6 |
7 | For example, a variable called `ekeArray` can hold basic information about a person called `Eke`.
8 |
9 | ### Note
10 |
11 | > It is a common practice to declare objects with the const keyword.
12 |
13 | ```js
14 | const ekeArray = [
15 | "Victor",
16 | "Eke",
17 | 2022 - 1997,
18 | "Programmer",
19 | ["Michael", "Peter", "Steven"],
20 | ];
21 | ```
22 |
23 | In arrays, we reference these values by their order number in which they appear, E.g `[0, 1, 2]` we can't reference them with a name. To solve that problem, we use objects.
24 |
25 | In objects, we define key value pairs. So we can give each value in the array a name.
26 |
27 | To do that we wrap the objects using curly brackets instead of the square brackets.
28 |
29 | ```js
30 | const eke = {
31 | firstName: "Jonas",
32 | lastName: "Jonas",
33 | age: 2022 - 1997,
34 | job: "Programmer",
35 | friends: ["Michael", "Peter", "Steven"],
36 | };
37 | ```
38 |
39 | The key here is the variable name on the left, followed by a colon and the value. The value can be any type we want. Key values are seperated by a comma just like in the arrays.
40 |
41 | We can see we created an object with 5 key value pairs. Now each of these keys are also called a property. So the example above `eke` has 5 properties.
42 |
43 | Objects are probably the most fundamental concepts in the whole JavaScript language, there are multiple ways of creating an object, but the easiest is the one we used in this example which is called the `object literal syntax`. This is called this way because, we are literally writing down the object content.
44 |
45 | The big difference between objects and arrays is that in an object, the order of the values does not matter when we want to retrieve the elements. Unlike arrays that are actually accessed using their order number.
46 |
47 | Therefore, we should use arrays for more ordered data and objects for more unstructured data, that we want to name and retrieve using that name.
48 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/10_introduction_to_objects/script.js:
--------------------------------------------------------------------------------
1 | const ekeArray = [
2 | "Victor",
3 | "Eke",
4 | 2022 - 1997,
5 | "Software Engineer",
6 | ["Michael", "Peter", "Steven"],
7 | ];
8 |
9 | const eke = {
10 | firstName: "Victor",
11 | lastName: "Eke",
12 | age: 2022 - 1997,
13 | job: "Software Engineer",
14 | friends: ["Michael", "Peter", "Steven"],
15 | };
16 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/11_dots_brackets_notation/README.md:
--------------------------------------------------------------------------------
1 | ## How to retieve elements from an Object
2 |
3 | In this section, we're going to learn how to retrieve and change data from an object using both the dot and bracket notation.
4 |
5 | ```js
6 | const eke = {
7 | firstName: "Victor",
8 | lastName: "Eke",
9 | age: 2022 - 1997,
10 | job: "Programmer",
11 | friends: ["Michael", "Peter", "Steven"],
12 | };
13 |
14 | console.log(eke);
15 | ```
16 |
17 | The values in an object is arranged alphabetically, but this doesn't matter because we simply get the properties from the object using the property name itself.
18 |
19 | There are two ways to do that, the `dot notation` and the `bracket notation`
20 |
21 | ## Dot Notation
22 |
23 | Now let's get the last name from our object array.
24 |
25 | ```js
26 | console.log(eke.lastName); // Get last name from the array
27 | ```
28 |
29 | This dot here is an operator that will go to this object and retrieve the property using the name we specified `(lastName)`
30 |
31 | ## Bracket Notation
32 |
33 | We can do the same thing using the brackets notation. It looks similar to how we retrieve data from an array but here we need to specify a string with the property name.
34 |
35 | ```js
36 | console.log(eke["lastName"]);
37 | ```
38 |
39 | Now the big difference between these two is that in the bracket notation `eke["name"]`, we can put an expression inside. So we don't have to explicitly write the string here, we can compute it from an operation.
40 |
41 | For example, imagine we have a variable in which we store a repeating part `(name)` in firstName and lastName.
42 |
43 | ```js
44 | const nameKey = "Name";
45 | console.log(eke["first" + nameKey]);
46 | console.log(eke["last" + nameKey]);
47 | ```
48 |
49 | JavaScript will start by executing the plus operation and create the string firstName and lastName.
50 |
51 | The same thing will not work with the dot notation.
52 |
53 | ## Situations to use dot Notation?
54 |
55 | - And when do we have to use the bracket notation.
56 |
57 | To recap what was said earlier, we use the bracket notation when we need to first compute the property name. In any other case, just use the dot notation which looks a lot cleaner and is easier to use.
58 |
59 | ### Bracket Notation Use Case
60 |
61 | Let's look at another example to make the need for the bracket notation even more clear.
62 |
63 | Let's say that we don't know yet which property we want to show, instead we get this from some user interface, what we can do is:
64 |
65 | ```js
66 | const interestedIn = prompt(
67 | "What do you want to know about Eke? Choose between firstName, lastName, age, job, and friends"
68 | );
69 | console.log(eke[interestedIn]);
70 | ```
71 |
72 | Here the `eke` object will replace the `interestedIn` variable with the values in the string.
73 |
74 | If we use the bracket notation, we get and `Undefined` error. This errors happens anytime we try to access a property on an object that does not exist. In our example, eke does not have a property called `interestedIn`
75 |
76 | Instead of using the dot notation, we use the bracket notation. Because then we can put any expression here, which will be interestedIn.
77 |
78 | Now if we pass in a propery or value that is not available in the object, we also get an undefined errorr. We can of course write a logic that will print a custom string whenever the user tries to access a property that doesn't exisit.
79 |
80 | ```js
81 | if (eke[interestedIn]) {
82 | console.log(eke[interestedIn]);
83 | } else {
84 | console.log(
85 | "Wrong request! Choose between firstName, lastName, age, job, and friends"
86 | );
87 | }
88 | ```
89 |
90 | ## Adding new properties to an object?
91 |
92 | - Using the dot and bracket notation.
93 |
94 | ```js
95 | eke.location = "Nigeria"; // dot notation
96 | eke["twitter"] = "@evavic44"; // bracket notation
97 | console.log(eke);
98 | ```
99 |
100 | ## Challenge
101 |
102 | Write a code to print the string below, dynamically.
103 | `"Eke has 3 friends, and his best friend is called Michael"`
104 |
105 | ```js
106 | console.log(
107 | `${eke.lastName} has ${eke.friends.length} friends, and the name of his best friend is ${eke.friends[0]}`
108 | );
109 | ```
110 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/11_dots_brackets_notation/script.js:
--------------------------------------------------------------------------------
1 | const eke = {
2 | firstName: "Victor",
3 | lastName: "Eke",
4 | age: 2022 - 1997,
5 | job: "Programmer",
6 | friends: ["Nikolas", "Spiff", "Crusoe"],
7 | };
8 |
9 | console.log(eke);
10 |
11 | // Dot Notation
12 | console.log(eke.lastName); // Get last name from the array
13 |
14 | // Bracket Notation
15 | console.log(eke["lastName"]);
16 |
17 | const nameKey = "Name";
18 | console.log(eke["first" + nameKey]);
19 | console.log(eke["last" + nameKey]);
20 |
21 | // Or
22 |
23 | console.log(eke[`first${nameKey}`]);
24 | console.log(eke[`last${nameKey}`]);
25 |
26 | const interestedIn = prompt(
27 | "What do you want to know about Eke? Choose between firstName, lastName, age, job, and friends"
28 | );
29 | console.log(eke[interestedIn]);
30 |
31 | // Logic to print a string if value is not in the object
32 | if (eke[interestedIn]) {
33 | console.log(eke[interestedIn]);
34 | } else {
35 | console.log(
36 | "Wrong request! Choose between firstName, lastName, age, job, and friends"
37 | );
38 | }
39 |
40 | // Add new properties to an object?
41 | eke.location = "Nigeria"; // dot notation
42 | eke["twitter"] = "@evavic44"; // bracket notation
43 | console.log(eke);
44 |
45 | // Challenge
46 | console.log(
47 | `${eke.lastName} has ${eke.friends.length} friends, and the name of his best friend is ${eke.friends[0]}`
48 | );
49 |
50 | // or
51 | console.log(
52 | eke.firstName +
53 | " has " +
54 | eke.friends.length +
55 | " friends, and his best friend is called " +
56 | eke.friends[0]
57 | );
58 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/12_object_methods/script.js:
--------------------------------------------------------------------------------
1 | const eke = {
2 | firstName: "Victor",
3 | lastName: "Eke",
4 | birthYear: 1997,
5 | job: "Programmer",
6 | friends: ["Nikolas", "Spiff", "Crusoe"],
7 | hasDriversLicense: true,
8 |
9 | // calcAge: function (birthYear) {
10 | // 2022 - birthYear;
11 | // },
12 |
13 | // calcAge: function () {
14 | // console.log(this)
15 | // return 2022 - this.birthYear;
16 | // },
17 |
18 | calcAge: function () {
19 | this.age = 2022 - this.birthYear;
20 | return this.age;
21 | },
22 |
23 | getSummary: function () {
24 | return `${this.firstName} is a ${this.calcAge()} year old ${
25 | this.job
26 | }, and he has ${this.hasDriversLicense ? "a" : "no"} drivers license`;
27 | },
28 | };
29 |
30 | console.log(eke.calcAge());
31 |
32 | console.log(eke.age);
33 | console.log(eke.age);
34 | console.log(eke.age);
35 |
36 | // Challenge
37 | // Victor is a 25 year old Programmer, and he has a(no) driver's license.
38 | console.log(eke.getSummary());
39 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/13_coding_challenge/README.md:
--------------------------------------------------------------------------------
1 | ## Coding Challenge 3
2 |
3 | Let's go back to Mark and John comparing their BMIs!
4 | This time, let's use objects to implement the calculations!
5 |
6 | ### Remember
7 |
8 | `BMI = mass / height **2 = mass / (height * height).`
9 | Mass in `kg` and height in `meter`.
10 |
11 | 1. For each of them, create an object with properties for their full name, mass, and height (Mark Miller and John Smith).
12 | 2. Create a `calcBMI` method on each object to calculate the `BMI` (the same method on both objects). Store the `BMI` value to a property, and also return it from the method.
13 | 3. Log to the console who has the higher BMI, together with the full name and the respective BMI.
14 |
15 | ### Example:
16 |
17 | `"John Smith's BMI (28.3) is higher than Mark Miller's (23.9)!"`
18 |
19 | ### Test Data:
20 |
21 | Marks weighs `78kg` and is `1.69m` tall. John weighs `92kg` and is `1.95m` tall.
22 |
23 | Gooluck 😁
24 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/13_coding_challenge/script.js:
--------------------------------------------------------------------------------
1 | /* ## Coding Challenge 3
2 |
3 | Let's go back to Mark and John comparing their BMIs!
4 | This time, let's use objects to implement the calculations!
5 |
6 | ### Remember
7 |
8 | `BMI = mass / height **2 = mass / (height * height).`
9 | Mass in `kg` and height in `meter`.
10 |
11 | 1. For each of them, create an object with properties for their full name, mass, and height (Mark Miller and John Smith).✅
12 | 2. Create a `calcBMI` method on each object to calculate the `BMI` (the same method on both objects). Store the `BMI` value to a property, and also return it from the method.
13 | 3. Log to the console who has the higher BMI, together with the full name and the respective BMI.
14 |
15 | ### Example:
16 |
17 | `"John Smith's BMI (28.3) is higher than Mark Miller's (23.9)!"`
18 |
19 | ### Test Data:
20 |
21 | Marks weighs `78kg` and is `1.69m` tall. John weighs `92kg` and is `1.95m` tall.
22 |
23 | Gooluck 😁
24 | */
25 |
26 | const mark = {
27 | fullName: "Mark Miller",
28 | mass: 78,
29 | height: 1.69,
30 |
31 | calcBMI: function () {
32 | this.bmi = this.mass / (this.height * this.height);
33 | return this.bmi;
34 | },
35 | };
36 |
37 | console.log(mark.calcBMI());
38 |
39 | const john = {
40 | fullName: "John Smith",
41 | mass: 92,
42 | height: 1.95,
43 |
44 | calcBMI: function () {
45 | this.bmi = this.mass / (this.height * this.height);
46 | return this.bmi;
47 | },
48 | };
49 |
50 | console.log(john.calcBMI());
51 |
52 | if (mark.bmi > john.bmi) {
53 | console.log(
54 | `${mark.fullName}'s BMI ${mark.bmi} is higher than ${john.fullName}'s BMI ${john.bmi}!`
55 | );
56 | } else {
57 | console.log(
58 | `${john.fullName}'s BMI ${john.bmi} is higher than ${mark.fullName}'s BMI ${mark.bmi}!`
59 | );
60 | }
61 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/14_Iteration_the_for_loop/README.md:
--------------------------------------------------------------------------------
1 | ### Iteration: The for Loop
2 |
3 | We talked about `if/else` statements in previous lectures about how they are control structures. Another control structure we have are `loops`
4 |
5 | ### What are loops
6 |
7 | Loops are a fundamental aspect of every programming language that allows us to automate repetitive tasks; Tasks we have to perform over and over again.
8 |
9 | ### Example
10 |
11 | Let's say we are trying to represent a repeated weight lifting exercise. This is how we will do it. In other to repeat this process, we have to but this violates the "don't repeat yourself(DRY)" principle because we're repeating the code 10 times and we're only changing the numbers.
12 |
13 | ```js
14 | console.log("Lifting weights repetition 1 🏋🏽");
15 | console.log("Lifting weights repetition 2 🏋🏽");
16 | console.log("Lifting weights repetition 3 🏋🏽");
17 | console.log("Lifting weights repetition 4 🏋🏽");
18 | console.log("Lifting weights repetition 5 🏋🏽");
19 | console.log("Lifting weights repetition 6 🏋🏽");
20 | console.log("Lifting weights repetition 7 🏋🏽");
21 | console.log("Lifting weights repetition 8 🏋🏽");
22 | console.log("Lifting weights repetition 9 🏋🏽");
23 | console.log("Lifting weights repetition 10 🏋🏽");
24 | ```
25 |
26 | So instead of doing the above, we can now create a `loop` and put only one of the line of code there and the loop will run the code over and over again until we tell it to stop.
27 |
28 | ### For Loop
29 |
30 | So we'll use the `for` loop, which has a counter for this. Just like a function, we'll use `for()` keyword with an open parenthesis.
31 |
32 | The loop statement has 3 parts, namely:
33 |
34 | 1. The initial value of a counter `in our example(1)`
35 | 2. The logical condition that is evaluated before each iteration of the loop(each time before the loop is executed). For example: if this condition `rep <= 10` is true, then the next loop iteration will run.
36 |
37 | > **Note** > `rep` here is short for repition so you can name your varaible whatever you want.
38 |
39 | But as soon as this condition is false, then the loop stops. (normal code will be executed). In summary,
40 |
41 | > The loop will keep running while the condition is true.
42 |
43 | 3. And the final part is used to increase the counter for each iteration. To do this, we increase rep with 1 for each iteration. Example: `rep = rep + 1`, `rep++` for shorts
44 |
45 | ```js
46 | for (let rep = 1; rep <= 10; rep++);
47 | ```
48 |
49 | And the final part we need to do is write the code that needs to be repeated.
50 |
51 | ```js
52 | for (let rep = 1; rep <= 10; rep++) {
53 | console.log("Lifting weights repetition 1 🏋🏽");
54 | }
55 | ```
56 |
57 | Finally, we can use template literals to append the number so we know the loop is working.
58 |
59 | ```js
60 | console.log(`Lifting weights repition ${rep} 🏋🏽`);
61 | ```
62 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/14_Iteration_the_for_loop/script.js:
--------------------------------------------------------------------------------
1 | // console.log("Lifting Weights repition 1 🏋🏽");
2 | // console.log("Lifting Weights repition 2 🏋🏽");
3 | // console.log("Lifting Weights repition 3 🏋🏽");
4 | // console.log("Lifting Weights repition 4 🏋🏽");
5 | // console.log("Lifting Weights repition 5 🏋🏽");
6 | // console.log("Lifting Weights repition 6 🏋🏽");
7 | // console.log("Lifting Weights repition 7 🏋🏽");
8 | // console.log("Lifting Weights repition 8 🏋🏽");
9 | // console.log("Lifting Weights repition 9 🏋🏽");
10 | // console.log("Lifting Weights repition 10 🏋🏽");
11 |
12 | // for ([initialExpression]; [conditionExpression]; [incrementExpression]) statement
13 |
14 | for (let rep = 1; rep <= 30; rep++) {
15 | console.log(`Lifting Weights repition ${rep} 🏋🏽`);
16 | }
17 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/15_looping_arrays_breaking_continuing/README.md:
--------------------------------------------------------------------------------
1 | ## Looping Arrays, Breaking and Continuing
2 |
3 | One of the most used applications of `for()` loops is looping through arrays.
4 |
5 | For example, let's say we want to loop through the array below and individually log every element of the array to the console.
6 |
7 | ```js
8 | const eke = [
9 | "Victor",
10 | "Eke",
11 | 2022 - 1997,
12 | "Programmer",
13 | ["Spiff", "Nick", "Jay"],
14 | ];
15 | ```
16 |
17 | > **Note**
18 | > In loops, the traditional name for counters is `i`
19 |
20 | As usual, we'll start the counter from `0`, and that is because arrays are zero-based when it comes to reading the elements.
21 |
22 | Next, we'll write our condition and finally increase the counter by `1`.
23 |
24 | Inside the loop, we'll write the code we want to be executed. Remember all we want to log is each element of the array. We can do that by simply doing this:
25 |
26 | ```js
27 | console.log(eke[0])
28 | console.log(eke[1])
29 | console.log(eke[2])
30 | ...
31 | console.log(4)
32 | ```
33 |
34 | But instead of hard-coding the zero, we will use the counter varaible.
35 |
36 | For the condition, we want to run the loop when `i` is `0, 1, 2, 3, 4,`. Here `4` is the last element since arrays are counted from `0`. So at `5` the loop will no longer run.
37 |
38 | ```js
39 | // console.log(eke[5]) does not exist.
40 | ```
41 |
42 | So the condition will be
43 |
44 | ```js
45 | // Run the loop if the position is 0 or less than 5
46 | i < 5;
47 | ```
48 |
49 | ```js
50 | for (let i = 0; i < 5; i++) {
51 | console.log(eke[i]);
52 | }
53 | ```
54 |
55 | Doing this will work, however, when we update the array by adding or removing an element, the counter does not get updated automatically.
56 |
57 | So to fix that, we'll use the array method `.lenght()` to dynamically check any changes made to the array.
58 |
59 | ```js
60 | for (let i = 0; i < eke.length; i++) {
61 | console.log(eke[i]);
62 | }
63 | ```
64 |
65 | And that's how you read values of an array using the `for()` loop. We can also create a new array based on the value of the previous array.
66 |
67 | ```js
68 | const types = [];
69 |
70 | for (let i = 0; i < eke.length; i++) {
71 | // Reading from eke array
72 | console.log(eke[i], typeof eke[i]);
73 |
74 | // Filling the types array
75 | types[i] = typeof eke[i];
76 |
77 | // Can also use the push menthod to add the elements at the end of the array.
78 | types.push(typeof eke[i]);
79 | }
80 |
81 | console.log(types);
82 | ```
83 |
84 | > **Important**
85 | > When pushing elements to an array, make sure you add it to the end of the array using `push()` and not the beginning using `unshift()`.
86 |
87 | ### In Summary
88 |
89 | - The loop starts with the counter being 0
90 | - The condition specifies the current index always needs to stay below the lenght of the array that we're looping through.
91 | - In the loop itself, we always get the current element using the current counter. `(0 to the lenght of the array)`
92 |
93 | A more practical example is to calculate the age from an array of birth years.
94 |
95 | ```js
96 | const years = [1997, 2007, 1969, 2020];
97 | const ages = [];
98 |
99 | for (let i = 0; i < years.length; i++) {
100 | ages.push(2022 - years[i]);
101 | }
102 |
103 | console.log(ages);
104 | ```
105 |
106 | > **Note**
107 | > Repeating the counter name(i) does not affect the previous counter.
108 |
109 | ### Continue and Break Statements
110 |
111 | The continue statement is used to exit the current iteration of the loop and move to the next one.
112 |
113 | Break is used to completely terminate the whole loop.
114 |
115 | ### Example Continue
116 |
117 | Let's say for instance we want to print only elements from the loop that are strings, we can use the continute statement for that.
118 |
119 | Here we created an if condition to check if the `typeof` of the element is not a string, then we want to continue. So this means the current iteration of the loop is exited and the next one starts immediately.
120 |
121 | ```js
122 | // ONLY STRINGS
123 | for (let i = 0; i < eke.length; i++) {
124 | if (typeof eke[i] !== "string") continue;
125 |
126 | console.log(eke[i], typeof eke[i]);
127 | }
128 | ```
129 |
130 | So this will skip any element in the array that is not a string, and then `continue` till the end of the iteration.
131 |
132 | ### Example - Break
133 |
134 | We can use the break statement if we want to end the iteration after a condition is true.
135 |
136 | ```js
137 | // BREAK WITH NUMBER
138 | for (let i = 0; i < eke.length; i++) {
139 | if (typeof eke[i] === "number") break;
140 |
141 | console.log(eke[i], typeof eke[i]);
142 | }
143 | ```
144 |
145 | In this example, as soon as the number is found, the loop breaks(stop).
146 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/15_looping_arrays_breaking_continuing/script.js:
--------------------------------------------------------------------------------
1 | const eke = [
2 | "Victor",
3 | "Eke",
4 | 2022 - 1997,
5 | "Programmer",
6 | ["Spiff", "Nicholas", "Jay"],
7 | true,
8 | ];
9 |
10 | const types = [];
11 |
12 | // console.log(eke[0])
13 | // console.log(eke[1])
14 | // ...
15 | // console.log(eke[4])
16 | // eke[4] does not exisit
17 |
18 | for (let i = 0; i < eke.length; i++) {
19 | // Reading from eke array
20 | console.log(eke[i], typeof eke[i]);
21 |
22 | // Filling types array
23 | // types[i] = typeof eke[i];
24 |
25 | // Can also use the push method to add the elements at the end of the array
26 | types.push(typeof eke[i]);
27 | }
28 | console.log(types);
29 |
30 | // Calculate the age of the following birthYear using loops
31 | const years = [1997, 2007, 1969, 2020];
32 | const ages = [];
33 |
34 | for (let i = 0; i < years.length; i++) {
35 | // in each iteration, the calculation is done individually so: years[0], years[1] ... years[3] is same as years[i]
36 | ages.push(2022 - years[i]);
37 | }
38 | console.log(ages);
39 |
40 | //? Continue and Break Statements
41 | //* Continue
42 | // The continue statement is used to exit the current iteration of the loop and move to the next one.
43 |
44 | //* Break
45 | // While the break statement is used to end an iteration after a condition is true.
46 |
47 | console.log("🔸ONLY STRINGS🔸");
48 | for (let i = 0; i < eke.length; i++) {
49 | // If the current element is not a string, skip over(continue) to the next line
50 | if (typeof eke[i] !== "string") continue;
51 | console.log(eke[i], typeof eke[i]);
52 | }
53 |
54 | console.log("🔸BREAK WITH NUMBER🔸");
55 | for (let i = 0; i < eke.length; i++) {
56 | // Once a number is found in the iteration, end(break) the loop
57 | if (typeof eke[i] === "number") break;
58 | console.log(eke[i], typeof eke[i]);
59 | }
60 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/16_looping_backwards_and_loops_in_loops/script.js:
--------------------------------------------------------------------------------
1 | //? Looping backwards
2 | //* Normal loop: 0, 1, ..., 4
3 | //* Backwards loop: 4, 3, ..., 1
4 |
5 | const eke = [
6 | "Victor",
7 | "Eke",
8 | 2022 - 1997,
9 | "Teacher",
10 | ["Spiff", "Nick", "Zod"],
11 | true,
12 | ];
13 |
14 | // Instead of hard-coding the counter(4), we use the .length method to get the total number of items in the array.
15 |
16 | // Length: eke.lenght - 1;
17 |
18 | // The condition: The loop should keep running if the counter is greater than or equal to 0(i >= 0);
19 |
20 | // Counter Update: Since we're looping backwards, we'll decrease the value of the counter: i--
21 | for (let i = eke.length - 1; i >= 0; i--) {
22 | console.log(i, eke[i]);
23 | }
24 |
25 | //? Loops inside of loops
26 | // A loop that runs three times from 1 - 3 and then another loop for each individual loop to run each 5 times to give a total of 15 loops, 5 for each.
27 | for (let exercise = 1; exercise < 4; exercise++) {
28 | console.log(`--------- Starting exercise ${exercise}`);
29 |
30 | for (let rep = 1; rep < 6; rep++) {
31 | console.log(`Exercise ${exercise}: Repition ${rep} 🏃🏽`);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/17_while_loop/script.js:
--------------------------------------------------------------------------------
1 | // for (let rep = 1; rep <= 10; rep++) {
2 | // console.log(`Lifting weights repition ${rep} 🏋🏽`);
3 | // }
4 |
5 | // It's called a while loop because it runs while a condition is true. Just like the for() loop, it requires the counter, the condition and a counter update.
6 |
7 | // Unlike the for() loop, while() loop requires the counter and counter update to be explicitly defined outsied of the loop.
8 |
9 | let rep = 1;
10 | while (rep <= 10) {
11 | // console.log(`WHILE: Lifting weights repition ${rep} 🏋🏽`);
12 | rep++;
13 | }
14 |
15 | // The while loop is more versatile than the for loop, it can be used in a wider variatey of situations, and this is because it does not need a counter. All it needs is a conditon for it to keep running.
16 |
17 | let dice = Math.trunc(Math.random() * 6 + 1);
18 |
19 | while (dice !== 6) {
20 | console.log(`You rolled a ${dice}`);
21 | dice = Math.trunc(Math.random() * 6 + 1);
22 |
23 | if (dice === 6) {
24 | console.log(`The loop is about to end 6️⃣`);
25 | }
26 | }
27 |
28 | //! Use the while() loop when you don't know how many iterations the loop will have, and the for() loop when you do know.
29 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/18_coding_challenge/README.md:
--------------------------------------------------------------------------------
1 | ## Coding Challenge
2 |
3 | Let's improve Steven's tip calculator even more, this time using loops.
4 |
5 | 1. Create an array `bills` containing all 10 test bill values.
6 | 2. Create empty arrays for the tips and the totals (`tips` and `totals`)
7 | 3. Use the `calcTip` function we wrote before (no need to repeat) to calculate tips and total values (bill + tip) for every bill value in the bills array.
8 | Use a for loop to perform the 10 calculations!
9 |
10 | ```js
11 | TEST DATA: 22, 295, 176, 440, 37, 105, 10, 1100, 86 and 52
12 | ```
13 |
14 | Hint: Call `calcTip` in the loop and use the push method to add values to the tips and totals arrays 🙃
15 |
16 | 4. BONUS: Write a function `calcAverage` which takes an array called `arr` as an argument. This function calculates the average of all numbers in the given array.
17 |
18 | This is a DIFFICULT challenge (we haven't done this before)!
19 |
20 | ### Hint
21 |
22 | 4.1. First, you will need to add up all values in the array. To do the addition, start by creating a variable 'sum' that starts at 0. Then loop over the array using a for loop.
23 |
24 | In each iteration, add the current value to the `sum` variable. This way, by the end of the loop, you have all values added together.
25 |
26 | 4.2 To calculate the average, divide the sum calculated before by the length of the array (because that's the number of elements).
27 |
28 | 4.3. Call the function with the `totals` array.
29 |
30 | Good Luck 🙃
31 |
--------------------------------------------------------------------------------
/02-Fundamentals-Part-2/18_coding_challenge/script.js:
--------------------------------------------------------------------------------
1 | const bills = [22, 295, 176, 440, 37, 105, 10, 1100, 86, 52];
2 | const tips = [];
3 | const totals = [];
4 |
5 | const calcTip = function (bill) {
6 | return bill >= 50 && bill <= 300 ? (15 / 100) * bill : (20 / 100) * bill;
7 | };
8 |
9 | // Tip & Bill values
10 | for (let i = 0; i < bills.length; i++) {
11 | const tip = calcTip(bills[i]);
12 | tips.push(tip);
13 | totals.push(tip + bills[i]);
14 | }
15 | console.log("Tips:", tips);
16 | console.log("Totals:", totals);
17 |
18 | // Average
19 | const calcAverage = function (arr) {
20 | let sum = 0;
21 | for (let i = 0; i < arr.length; i++) {
22 | sum += arr[i];
23 | }
24 | return sum / arr.length;
25 | };
26 |
27 | console.log(calcAverage(totals));
28 |
--------------------------------------------------------------------------------
/03_Developers-Skills/How_to_solve_problems.md:
--------------------------------------------------------------------------------
1 | ## How to effectievly solve problems
2 |
3 | 1. Make sure you 100% understand the problem. **Ask the right questions** to get a clear picture.
4 |
5 | ### Example
6 |
7 | **💬Project Manager: We need a function that reverses whatever we pass into it.**
8 |
9 | **Questions**
10 |
11 | - What does "whatever" even mean in this context? What should be reversed?
12 | **Answer:** Only strings, numbers, and arrays make sense to reverse
13 |
14 | - What to do if something else is passed in?
15 | - What should be returned? Should it always be a string, or should the type be the same as passed in?
16 | - How to recognize wether the argument is a number, a string, or an array?
17 | - How to reverse a number, a string, and an array?
18 |
19 | 2. **Divide and Conquer**: Break a big problem into smaller sub-problems.
20 |
21 | ### Sub problems:
22 |
23 | - Check if arugment is a number, a string, or an array
24 | - Implement reversing a number
25 | - Implemement reversing a string
26 | - Implement reversing an array
27 | - Return reversed value
28 |
29 | 3. Don't be afraid to do as much **research** as you have to.
30 |
31 | ### Example
32 |
33 | - How to check if a value is a number in JavaScript.
34 | - How to check if a value is a string in JavaScript.
35 | - How to check if a value is an array in JavaScript.
36 | - How to reverse a number in JavaScript.
37 | - How to reverse a string in JavaScript.
38 | - How to reverse an array in JavaScript.
39 |
40 | 4. For bigger problems, **write pseudo-code** before writing the actual code.
41 |
42 | ```
43 | Sudo code is an informal description of the actual code we need to write that humans can understand.
44 | ```
45 |
46 | ```js
47 | function reverse(value)
48 | if value type !string && !number && !array
49 | return value
50 |
51 | if value type == string
52 | reverse string
53 |
54 | if value type == number
55 | reverse number
56 |
57 | if value type == array
58 | reverse array
59 |
60 | return reversed value
61 | ```
62 |
63 | ## What is a Software Bug?
64 |
65 | A bug is a defect or problem in a computer program. Basically, any **unexpected or unintended behavior** of a computer program is a software bug.
66 |
67 | Bugs are **completelty normal** in software development.
68 |
69 | ### Debugging
70 |
71 | This is the process of finding, fixing and preventing bugs.
72 |
73 | ### 1. INDENTIFY
74 |
75 | Ways bugs are indentified.
76 |
77 | - During development.
78 | - Using testing software.
79 | - User reports during production.
80 | - Context browsers, users, etc.
81 |
82 | ### 2. FIND
83 |
84 | - Developer console (simple code).
85 | - Debugger (complex code).
86 |
87 | ### 3. FIX
88 |
89 | - Replace wrong solution with new correct solution.
90 |
91 | ### 4. PREVENT
92 |
93 | - Searching for the same bug in similar code.
94 | - Writing tests using testing software.
95 |
96 | ## Debugging with the console and Breakpoints
97 |
98 | We have other `console` funtions
99 |
100 | ```js
101 | console.log(); // normal result
102 | console.warn(); // for showing result as warnings
103 | console.error(); // for showing results as errors
104 | ```
105 |
106 | We also have another special `console` function
107 |
108 | ```js
109 | console.table();
110 | ```
111 |
112 | This is used for showing objects in a tabular format. Pretty handy for bigger objects.
113 |
--------------------------------------------------------------------------------
/03_Developers-Skills/challenge.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /* Given an array of forecasted maximum temperatures, the thermometer displays a string with these temperatures.
4 |
5 | Example: [17, 21, 23] will print "...17°c in 1 days ...21°c in 2 days ...23°c in 3 days..."
6 |
7 | Create a function 'printForecast' which takes in an array 'arr' and logs a string like the above to the console.
8 |
9 | Use the problem-solving framework: Understand the problem and break it up into sub-problems!
10 |
11 | ? TEST DATA 1: [17, 21, 23]
12 | ? TEST DATA 2: [12, 5, -5, 0, 4]
13 | */
14 |
15 | /*
16 | 1. Understand the problem
17 | - What do you mean by maximum temperatures?
18 | All the temperatures in the array I guess.
19 |
20 | - What happens if the thermometer forecasts a negative value?
21 | Go ahead and print it as required.
22 |
23 | - Trailing dots before each value?
24 | - Does each array value signify a day?
25 |
26 | 2. Divide and conquer
27 | - Convert the numbers in the array to strings.
28 | - Concatenate the numbers with the degree symbol and the unit of celsius.
29 | - Loop through the values in the array and increase the day on each temperature by 1 day.
30 | - Log the value to the console.
31 |
32 | 3. Write sudo code
33 | Not required.
34 | */
35 |
36 | let arr = [17, 21, 23];
37 | const printForecast = function (arr) {
38 | for (let i = 0; i < arr.length; i++) {
39 | console.log(`...${arr[i]}°C in ${[i + 1]} days`);
40 | }
41 | };
42 |
43 | arr = [12, 5, -5, 0, 4];
44 | printForecast(arr);
45 |
46 | // JONAS Solution
47 | const data1 = [17, 21, 23];
48 | const data2 = [12, 5, -5, 0, 4];
49 |
50 | console.log("___JONAS SOLUTION___");
51 | console.log(`...${data1[0]}°C ...${data1[1]}°C ...${data1[2]}°C ...`);
52 |
53 | const printForecastJonas = function (arr) {
54 | let str = "";
55 | for (let i = 0; i < arr.length; i++) {
56 | str += `${arr[i]}°C in ${i + 1} days ...`;
57 | }
58 | console.log("..." + str);
59 | };
60 |
61 | printForecastJonas(data1);
62 |
--------------------------------------------------------------------------------
/03_Developers-Skills/script.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | //? PROBLEM 1
4 | // We work for a company building a smart home themometer. Our most recent task is this.
5 | // Given an array of tempratures of one day, calculate the temprature amplitude. Keep in mind that sometimes there might be a sensor error.
6 |
7 | const temperatures = [3, -2, -6, -1, "error", 9, 13, 17, 15, 14, 9, 5];
8 |
9 | //? 1. Understanding the problem
10 | // —What is temp amplitude? Answer: The difference between the highest and lowest temprature.
11 |
12 | // —How to compute max and min temperature?
13 | // What's a sensor error? And what do you do?
14 |
15 | //? 2. Breaking up into sub-problems
16 | // - How to ignore errors?
17 | // - Find max value in temp array
18 | // - Find min value in temp array
19 | // - Subtract min from max (amplitude) and return it.
20 |
21 | const calcTempAmplitude = function (temps) {
22 | let max = temps[0];
23 | let min = temps[0];
24 | for (let i = 0; i < temps.length; i++) {
25 | const currentTemp = temps[i];
26 | if (typeof currentTemp !== "number") continue;
27 |
28 | if (currentTemp > max) max = currentTemp;
29 | if (currentTemp < min) min = currentTemp;
30 | }
31 |
32 | console.log(max, min);
33 | return max - min;
34 | };
35 |
36 | const amplitude = calcTempAmplitude(temperatures);
37 | console.log(amplitude);
38 |
39 | //? PROBLEM 2
40 | // Function should now receive 2 arrays of tempertatures.
41 |
42 | //? 1. Understanding the problem
43 | // - With 2 arrays, should we implement functionality twice?
44 | // No just merge two arrays.
45 |
46 | //? 2. Breaking up into sub-problems
47 | // -Merge 2 arrays?
48 |
49 | const calcTempAmplitudeBug = function (t1, t2) {
50 | const temps = t1.concat(t2);
51 | console.log(temps);
52 |
53 | let max = 0;
54 | let min = 0;
55 | for (let i = 0; i < temps.length; i++) {
56 | const currentTemp = temps[i];
57 | if (typeof currentTemp !== "number") continue;
58 |
59 | if (currentTemp > max) max = currentTemp;
60 | if (currentTemp < min) min = currentTemp;
61 | }
62 |
63 | console.log(max, min);
64 | return max - min;
65 | };
66 |
67 | const amplitudeBug = calcTempAmplitudeBug([3, 5, 1], [9, 4, 5]);
68 | console.log(amplitudeBug);
69 |
70 | //! Debugging with the Console and Breakpoints
71 | const measureKelvin = function () {
72 | const measurement = {
73 | type: "temp",
74 | unit: "cels",
75 | // C. FIX
76 | // value: Number(prompt("Degrees Celsius:")),
77 | value: 10,
78 | };
79 |
80 | // B. FIND
81 | console.log(measurement);
82 | console.table(measurement);
83 | // console.log(measurement.value);
84 | // console.warn(measurement.value);
85 | // console.error(measurement.value);
86 |
87 | const kelvin = measurement.value + 273;
88 | return kelvin;
89 | };
90 |
91 | // A. IDENTIFY
92 | console.log(measureKelvin());
93 |
--------------------------------------------------------------------------------
/05-Guess-My-Number/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": false,
3 | "arrowParens": "avoid"
4 | }
5 |
--------------------------------------------------------------------------------
/05-Guess-My-Number/cheer.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Evavic44/Learn-JavaScript/927358ce7de6527b788948397986c6b32103a990/05-Guess-My-Number/cheer.mp3
--------------------------------------------------------------------------------
/05-Guess-My-Number/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
(Between 1 and 20)
14 | 15 |💯 Tries: 10
25 |26 | 🥇 Highscore: 0 27 |
28 |43
16 |Current
18 |0
19 |24
24 |Current
26 |0
27 |53 | As of 05/03/2037 54 |
55 |0000€
57 |In
78 |0000€
79 |Out
80 |0000€
81 |Interest
82 |0000€
83 | 84 |126 | You will be logged out in 05:00 127 |
128 |Current balance
44 |45 | As of 05/03/2037 46 |
47 |0000€
49 |In
70 |0000€
71 |Out
72 |0000€
73 |Interest
74 |0000€
75 | 76 |118 | You will be logged out in 05:00 119 |
120 |