# 822 WEB: JavaScript Fundamentals --- # Lesson 0: Setup ## How do I install JavaScript? :::info You **don't need to install JavaScript**; it comes with all browsers. ::: ## VSCode Extenstion Recommendations :::success - Auto Close Tag - Auto Rename Tag - Live Server - HTML CSS Support - HTML Snippets - JavaScript (ES6) code snippets ::: ## The Weird History of JavaScript {%youtube Sh6lK57Cuk4%} --- # Lesson 1: Introduction :::success [**sourse code: _01intro**](https://github.com/qiyoudaoyi/822-web-course/tree/main/JS/_01intro) ::: ## Let's review some HTML/CSS ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intro to JavaScript</title> <style> * { text-align: center; font-family: "cascadia code"; background-color: antiquewhite; } h1, h2 { background-color: aliceblue; } </style> </head> <body> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 1: Introduction</h2> <hr> </body> </html> ``` ## JavaScript in HTML - ### [__`intro.html`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_01intro/intro.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intro to JavaScript</title> <style> * { font-family: "cascadia code"; background-color: aliceblue; } h1, h2 { text-align: center; } </style> </head> <body> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 1: Introduction</h2> <hr> <script type="text/javascript"> document.write("hello world!"); </script> </body> </html> ``` - ### `<script></script>` :::info We can add our `script` inside the `<script></script>` tag as in `line 20 to 22`. ::: ```javascript=20 <script type="text/javascript"> document.write("hello world!"); </script> ``` - ### `type="text/javascript"` ::: info - It specifies what script we're using, in our case, it's `JavaScript`. - However, the `type` is __by-default `JavaScript`__, so it's __not necessary__. - ### The Semi-colon `;` :::info It's not needed , but __STRONGLY RECOMMENDED__. ::: - ### Three ways to output in webpages using JavaScript | # | Method | Destination | |---| --------------------| ------------------| | 1 | `console.log()` | browser's console | | 2 | `alert()` | pop-up alert | | 3 | `document.write()` | webpage | :::info You can access the browser's console by pressing `F12` on your keyboard. ::: ```javascript= console.log("hello world!"); alert("hello world!"); document.write("hello world!"); ``` --- # Lesson 2: External Files :::success [**sourse code: _02extfile**](https://github.com/qiyoudaoyi/822-web-course/tree/main/JS/_02extfile) ::: ## Remember how we seperate css stylesheets? - ### `<link rel="stylesheet" href="..\src\style.css">` :::info - The end tag is not necessary. - `rel="stylesheet"` specifies that the `<link>` tag links to a stylesheet. - `href="..\src\style.css"` tells the browser where to fetch the stylesheet. - ### [__`extfile.html`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_02extfile/extfile.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intro to JavaScript</title> <link rel="stylesheet" href="..\src\style.css"> </head> <body> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 2: External Files</h2> <hr> </body> </html> ``` - ### [__`..\src\style.css`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/src/style.css) ```css= * { font-family: "cascadia code"; background-color: aliceblue; } h1, h2 { text-align: center; } ``` ## Now we'll seperate JavaScript code - ### This is our JS file: [__`.\extfile.js`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_02extfile/extfile.js) ```javascript= document.write("hello world!"); ``` - ### `<script src=".\extfile.js"></script>` :::info `src="PATH"` tells the browser where to fetch the file. - ### [__`extfile.html`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_02extfile/extfile.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intro to JavaScript</title> <link rel="stylesheet" href="..\src\style.css" /> </head> <body> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 2: External Files</h2> <hr> <script src=".\extfile.js"></script> </body> </html> ``` - ### Where you put `<script src=".\extfile.js"></script>` matters :::info The browsers read code **line by line**. ::: - ### [__`extfile.html`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_02extfile/extfile.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Intro to JavaScript</title> <link rel="stylesheet" href="..\src\style.css" /> </head> <body> <script src=".\extfile.js"></script> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 2: External Files</h2> <hr> </body> </html> ``` --- # Lesson 3: Variables :::success [**sourse code: _03variables**](https://github.com/qiyoudaoyi/822-web-course/tree/main/JS/_03variables) ::: ## Let's warm up a bit :::danger ### First of all, in most programming languages,<br><br>`=` DOES NOT mean "EQUAL TO";<br>`=` means "ASSIGNMENT" ::: - ### [__`var_warmup.html`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/warmup/var_warmup.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Lesson 3: Variables (Warmup)</title> <link rel="stylesheet" href="..\src\style.css"> </head> <body> <h1>822 WEB Course</h1> <h1>JavaScript Programming</h1> <h2>Lesson 3: Variables (Warmup)</h2> <hr> <script src="var_warmup.js"></script> </body> </html> ``` - ### [__`.\var_warmup.js`__](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/warmup/var_warmup.js) ```javascript= const my_name = 'Wilson'; const my_age = 20; const my_hobby = 'coding'; document.write('I am ' + my_name + ', and I am ' + my_age + ' years old, and I like ' + my_hobby + '.'); document.write('<br>') document.write('<p>' + 'I am ' + my_name); document.write(', and I am ' + my_age + ' years old'); document.write(', and I like ' + my_hobby + '.' + '</p>'); ``` ## Variables Declarations > ### There are three ways to declare a variable: > - `var` > - `let` > - `const` ### `var` - ### Scope of `var`: :::info - `global scope` if declared outside a function. - `function scope` if declared inside a function. ::: - ### `var` can be **re-declared** ```javascript var x = 213; // x is declared as a number var x = "Hello!"; // x is re-declared as a string ``` - ### `var` can be **updated** ```javascript var x = 213; // x is declared as a number x = "Hello!"; // x is now a string ``` - ### `var` can be declared without initialized ```javascript var x; // x is declared but undefined x = 213; // x is now a number ``` ### `let` - ### Scope of `let` is block scope :::info Accessible only within `{}` ::: - ### `let` can **NOT** be re-declared ```javascript let x = 213; // x is declared as a number let x = "Hello!"; // ERROR ``` :::danger `❌ Uncaught SyntaxError: Identifier 'x' has already been declared` ::: - ### `let` can be **updated** ```javascript let x = 213; // x is declared as a number x = "Hello!"; // x is now a string ``` - ### `let` can be declared without initialized ```javascript let x; // x is declared but undefined x = 213; // x is now a number ``` ### `const` - ### Scope of `const` is block scope :::info Accessible only within `{}` - ### `const` can **NOT** be re-declared ```javascript const x = 213; // x is declared as a number const x = "Hello!"; // ERROR ``` :::danger `❌ Uncaught SyntaxError: Identifier 'x' has already been declared` ::: - ### `const` can **NOT** be updated ```javascript const x = 213; // x is declared as a number x = "Hello!"; // ERROR ``` :::danger `❌ Uncaught TypeError: Assignment to constant variable` ::: - ### `const` **MUST be initialized upon declaration** ```javascript const x; // ERROR ``` :::danger `❌ Uncaught SyntaxError: Missing initializer in const declaration` ::: ### Summary | declartions | re-declaration | update | MUST be initialized when declared| |-------------|----------------|--------|----------------------------------| | `var` | ✔ | ✔ | ➖ | | `let` | ❌ | ✔ | ➖ | | `const` | ❌ | ❌ | ✔ | :::success 💯 **Use `const` and `let` when possible** ::: ## Variables Types > ### There are `7 primitive types`, and `1 object type`. - ### `Number`(Lesson 3) :::success Integers or floating point numbers - `213`, `6.97`, `4.5e-23`, `2.6e7` ::: - ### `BigInt` :::warning Numbers that are larger than `2e53-1` or smaller than `-(2e53-1)` - `1234567890123456789012345678901234567890n` ::: - ### `String` (Lesson 3) :::success A seqence of charactors surrounded by single or double quotes - `'822'`, `"ColdeGarage"`, `'senpai is handsome!'` ::: - ### `Boolean` (Lesson 4) :::success Logical type - `true`, `false` ::: - ### `null` :::success Value unknown - `null` ::: - ### `undefined` :::success Value undefined - `undefined` ::: - ### `Symbol` :::warning **UNIQUE** identifier - `Symbol('822')`, `Symbol('ColdeGarage')` ::: - ### `Object`(Lesson 7) :::success A collection of data, the data can be all 8 types. Basically, anything that's not primitive is an `object`. - `{name: 'Wilson', age: 20, favorite_food: 'chicken breast'}` ::: ## Operators - ### Arithmetic Operators | Operator | Description | |----------|-------------| | `+ ` | Addition | | `- ` | Subtraction | | `* ` | Multiplication | | `** ` | Exponentiation | | `/ ` | Division | | `% ` | Modulus (Remainder) | | `++ ` | Increment | | `-- ` | Decrement | - ### Assignment Operators | Operator | Example | Same as | |----------|---------|---------| | `= ` | `x = y ` | `x = y ` | | `+= ` | `x += y ` | `x = x + y ` | | `-= ` | `x -= y ` | `x = x - y ` | | `*= ` | `x *= y ` | `x = x * y ` | | `/= ` | `x /= y ` | `x = x / y ` | | `%= ` | `x %= y ` | `x = x % y ` | | `**=` | `x **= y` | `x = x ** y` | - ### Comparison Operators | Operator | Description | |----------|-------------| | `== ` | equal to | | `===` | equal value and equal type | | `!= ` | not equal | | `!==` | not equal value or not equal type | | `> ` | greater than | | `< ` | less than | | `>= ` | greater than or equal to | | `<= ` | less than or equal to | | `? ` | ternary operator | - ### Logical Operators | Operator | Description | |----------|-------------| | `&&` | Logical and | | `\|\|` | Logical or | | `!` | Logical not | ## Let's do some math with `Numbers`! :::success [**sourse code: _03variables\num.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/num.js) ::: - ### `Math.sqrt()` will return the square root of the number you put in. ```javascript= // I hope you still remember Pythagorean theorem let a = 3; let b = 4; let c_square; let c; c_square = a**2 + b**2; c = Math.sqrt(c_square); document.write('a = ' + a + ', b = ' + b + ',<br>'); document.write('c_square = a^2 + b^2 = ' + c_square + ',<br>'); document.write('c = ' + c + '.<br>'); ``` - ### You can also write expressions in the parameter instead. ```javascript document.write('c_square = a^2 + b^2 = ' + (a**2 + b**2) + ',<br>'); document.write('c = ' + Math.sqrt(a**2 + b**2) + '.<br>'); ``` - ### `Math.random()` will return a random `number` from 0 to 1. - ### `Math.floor()` will truncate the decimal part of a `number`. ```javascript=12 let random_num, random_die; random_num = Math.random(); random_die = Math.floor(Math.random() * 6 + 1); document.write(`random_num = ${random_num}<br/>`); document.write(`random_die = ${random_die}<br/>`); ``` ## Working with `Strings` :::success [**sourse code: _03variables\str.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/str.js) ::: - ### Setting up some variables: ```javascript= const my_name = 'Wilson'; const my_age = 20; const my_hobby = 'coding'; const alphabets_caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; ``` - ### String Template and Interpolation: :::info - Backticks(``) instead of quotes(`''` or `""`) - `${variable}` to substitute string ::: ```javascript=7 document.write(`<p>I am ${my_name}.</p><p>I am ${my_age} years old.</p><p>I like ${my_hobby}.</p>`); ``` - ### Index of a String: A sequence of charactors :::info - Starts at `0` - `undefined` beyond string length ::: - #### Example: ```javascript const my_name = 'Wilson'; // INDEX: 012345 const my_hobby = 'coding'; // INDEX: 012345 const alphabets_caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // INDEX: 0123456789... ``` - #### Let's try: ```javascript=10 document.write(my_name[0] + `<br>`); // W document.write(my_name[1] + `<br>`); // i document.write(my_name[2] + `<br>`); // l document.write(my_name[3] + `<br>`); // s document.write(my_name[4] + `<br>`); // o document.write(my_name[5] + `<br>`); // n document.write(my_name[6] + `<br>`); // undefined ``` - ### Some String Methods :::info - `.toLowerCase()`: Convert a string to lower case. - `.toUpperCase()`: Convert a string to upper case. - `.length`: Get the length of a string. ::: ```javascript=19 const alphabet_lower = alphabets_caps.toLowerCase(); document.write(alphabet_lower + `<br>`); document.write(alphabets_caps + `<br>`); document.write(my_hobby.length + `<br>`); document.write(alphabets_caps.length + `<br>`); ``` ## `Array` Hurray! :::success [**sourse code: _03variables\array.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/array.js) ::: > ### An array is a special variable that can hold multiple values at once. - ### Creating an Array: ```javascript= const students = ['Wilson', 'Tony', 'Bruce']; ``` - ### Index of an array (works like that of a string): ```javascript=3 document.write(students[0] + '<br/>'); students[0] = 'Peter'; document.write(students[0] + '<br/>'); document.write(students + '<br/>'); ``` - ### Some Array Methods :::info - `.length` returns the length of the array. - `.push()` adds an element at the end of the array. - `.unshift()` adds an element at the beginning of the array. ::: ```javascript=8 let l = students.length; document.write(l+ '<br/>'); students.push('Clint'); students.push('Scott'); document.write(students + '<br/>'); l = students.length; document.write(l+ '<br/>'); ``` :::info - `.pop()` delete the first element of the array. - `.shift()` delete the last element of the array. ::: ```javascript=16 students.pop(); students.shift(); document.write(students + '<br/>'); ``` :::info - `.sort()` sort the array in alphabetical order. - `.reverse()` does what it is called... ::: ```javascript=20 students.sort(); document.write(students + '<br/>'); students.reverse(); document.write(students + '<br/>'); ``` ## How Characters are Stored in Computers? {%youtube MijmeoH9LT4 %} ## Getting User's Input > ### Although we can use `<form></form>` together with `<input>`, let's do this the old-fashion way. - ### `window.prompt("descrpition")` :::info - Pops up a box with text area. - We can store that text as a **`string`** to a variable. ::: - ### [Example 1: The Greeting AI](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/prompt/prompt_str.js) ```javascript= const your_name = window.prompt("What is your name?"); const age = window.prompt("How old are you?"); const school = window.prompt("Where do you study?"); const major = window.prompt("What do you study?"); document.write(`Hello, ${your_name}, an undergrad in ${school} who majors in ${major}.<br/>`); document.write(`You are ${age} years old.<br/>`); ``` - ### If we need a `number` type, we must `parse` it. :::info - `parseInt(target)` - Convert `target` into an integer. - `parseFloat(target)` - Convert `target` into a floating point number. - ### [Example 2: A Simple Adder](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_03variables/prompt/prompt_num.js) - ### Not this adder by the way ![](https://i.imgur.com/vA5I8F3.png) ```javascript= let a = window.prompt("a ="); let b = window.prompt("b ="); a = parseFloat(a); b = parseFloat(b); let result = a + b; document.write(`${a} + ${b} = ${result}<br/>`); ``` # Exercise 1: Longest side of a Right Triangle ## Descrpition :::info Enter two number via `window.prompt()`, those two number are the lengths of side a and b in a right triangle, your job is to calculate the length of the longest side c. ::: ## Sample I/O | Input | Output | |---------------|-------------------------------------------| | `3` `4` | `a = 3 b = 4 c = 5` | | `5` `12` | `a = 5 b = 12 c = 13` | | `6.32` `56.7` | `a = 6.32 b = 56.7 c = 57.05113846366258` | ## [Reference Answer](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/Exercises) - ### [`ex1.html`](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/Exercises/ex1.html) ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Exercise 1</title> </head> <body> <script src="ex1.js"></script> </body> </html> ``` - ### [`ex1.js`](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/Exercises/ex1.js) ```javascript= let a = window.prompt("a ="); let b = window.prompt("b ="); let c; a = parseFloat(a); b = parseFloat(b); c = Math.sqrt(a**2 + b**2); document.write(`a = ${a} b = ${b} c = ${c}<br/>`); ``` --- # Lesson 4: Conditional Statements :::success [**sourse code: 04conditionalstatements**](https://github.com/qiyoudaoyi/822-web-course/tree/main/JS/_04conditional_statements) ::: ## The `if` Statement ### Syntax Cheatsheet :::info - ### `if` ```javascript if (condition) { // If condition is true, this block of code will be executed. } ``` - ### `if` ... `else` :::info ```javascript if (condition) { // If condition is true, this block of code will be executed. } else { // If condition is false, this block of code will be executed. } ``` - ### `if` ... `else if` ... `else` ```javascript if (condition 1) { // If condition 1 is true, this block of code will be executed. } else if (condition 2) { // If the condition 1 is false and condition2 is true, // this block of code will be executed. } else if (condition 3) { // If all conditions before condition 3 are false // and condition3 is true, // this block of code will be executed. ... } else { // If all conditions are false, this block of code will be executed. } ``` ::: ### A brief Introduction of `if` statement - ### In short, the `if` statement checks if an expression is `true` or `false`. When it's `true`, the code within will run. ```javascript if (5 > 3) { document.write(`hello!<br/>`); } if (2 < 2) { document.write(`WHAT!<br/>`); } if (true) { document.write(`TRUE!<br/>`); } if (false) { document.write(`FALSE!<br/>`); } > hello! > TRUE! ``` - ### But, what is `true`? ![](https://i.imgur.com/Ncd7Z40.jpg) ### Let's talk about `Boolean` :::success [**sourse code: _04conditional_statements/bool.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_04conditional_statements/bool.js) ::: > ### `Boolean` has only two value: `true` and `false` - ### You can explicitly assign `boolean` to a variable. ```javascript= const is_male = true; const do_drugs = false; document.write(is_male + '<br/>'); document.write(do_drugs + '<br/><br/>'); ``` - ### `boolean` is mostly attained by comparison. ```javascript=12 const result1 = (10 > 8); const result2 = (2 === 3); document.write(result1 + '<br/>'); document.write(result2 + '<br/><br/>'); ``` - ### Difference between `==` and `===` :::info - `==` EQUAL TO - Types are converted. **❌NAH** ```javascript 38 == 38; // true 25 == '25'; // true 0 == false; // true ``` - `===` **STRICT** EQUAL TO - Types are checked. **✅GOOD** ```javascript 38 === 38; // true 25 === '25'; // false 0 === false; // false ``` ::: :::danger **📌Tip**: Always use `===` to avoid bugs - ### There are also `!=` and `!==` :::info - `!=` NOT EQUAL TO - `!==` **STRICT** NOT EQUAL TO - ### Everything With a "Value" is `true` ```javascript=17 if (312344) { document.write(`TRUE!!!<br/>`); } if ('Wilson') { document.write(`TRUE!!!<br/>`); } ``` - ### Everything **Without** a "Value" is `false` ```javascript=24 if (0) { document.write(`ZERO IS TRUE??!!<br/>`); } if ('') { document.write(`EMPTY STRING IS TRUE??!!<br/>`); } ``` - ### Logical not `!` can get you the oppisite result. ```javascript=31 if (!'Wilson') { document.write(`WILSON!!!<br/>`); } if (!'') { document.write(`???!!!<br/>`); } if (!0) { document.write(`HUH!!!<br/>`); } ``` ### `if` ... `else if` ... `else` :::success [**sourse code: _04conditional_statements/if.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_04conditional_statements/if.js) ::: - ### Reference variables ```javascript= const name = 'Vivy'; const age = 100; const is_male = false; const purpose = 'bringing joy to people by singing'; const hobby = ''; const grade = 89; ``` - ### `if` :::info Execute the code inside `if` when a condition is met. ::: ```javascript=8 if (age >= 18) { document.write(`Oh my god! You're old!.<br/>`); } ``` :::success **📌Tip**: If there is only one line of code, we don't need the curly braces. ::: ```javascript if (age >= 18) document.write(`Oh my god! You're old!.<br/>`); ``` - ### `else` :::info When the condition is not met, however, execute another piece of code. ::: ```javascript=12 if (is_male) document.write(`Vivy is a man.<br/>`); else document.write(`Vivy is a woman.<br/>`); ``` - ### **`Boolean` Review** :::info We can also check if a "value" exists or not. ::: ```javascript=17 document.write(`Vivy's purpose is ${purpose}.<br/>`); if (hobby) document.write(`Vivy's hobby is ${hobby}.<br/>`); else document.write(`She has no hobbies.<br/>`); ``` - ### `else if` :::info We may have more than one conditions to check. ::: ```javascript=24 if (grade >= 80) document.write(`A<br/>`); else if (grade >= 70 && grade < 80) document.write(`B<br/>`); else if (grade >= 60 && grade < 70) document.write(`C<br/>`); else document.write(`D<br/>`); ``` ## The `switch` Statement :::success [**sourse code: _04conditional_statements/switch.js**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_04conditional_statements/switch.js) ::: ### Syntax Cheatsheet :::info ```javascript switch(expression) { case x: // code block break; case y: // code block break; default: // code block } ``` ::: <br> > ### There might be too many cases to check for `else if`, so we invent a new statement `switch` to deal with multiple conditions. > - ### `case (expression):` :::info `case` acts like a teleportation, we simply start our code from the case satisfied. ::: - ### `break` :::info - `break` stops the code and escape out of the `switch` statement. - Without `break`, the code will continue to run the remaining cases. ::: - ### `default` :::info - The code block inside `default` will run if no other cases **above** are satisfied. - `default` must be placed at the end of the `switch` statement. - No need to put `break` after `default` since it's the last piece of code. ::: - ### [**`\switch.js`**](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/_04conditional_statements/switch.js) ```javascript= const cardinal = window.prompt("Enter an Integer:"); const least_significant_bit = cardinal % 10; const tens_digit = Math.floor(cardinal / 10) % 10; let ordinal = toString(cardinal); switch (least_significant_bit) { case 1: if (tens_digit !== 1) ordinal += 'st'; else ordinal += 'th'; break; case 2: ordinal += 'nd'; break; case 3: ordinal += 'rd'; break; default: ordinal += 'th'; } document.write(`Cardinal form: ${cardinal}<br/>`); document.write(`Ordinal form: ${ordinal}<br/>`); ``` --- # Lesson 5: Loop :::success [**sourse code: _05loop**](https://github.com/qiyoudaoyi/822-web-course/tree/main/JS/_04loop) ::: ## It's warm-up time again! > ### Let's say we have an array of students and we want to print them out. - ### Review on how to create an array of students ```javascript const students = []; students.push('Wilson'); students.push('Angela'); students.push('Jessica'); students.push('Watson'); students.push('Holmes'); students.push('Ben'); students.push('Cindy'); ``` :::danger Note that `const` only forbids you from doing **REASSIGNMENT**. However, **modifying** its elements is allowed. ::: - ### We can print the entire array. ```javascript document.write(students); > [ 'Wilson', 'Angela', 'Jessica', 'Watson', 'Holmes', 'Ben', 'Cindy' ] ``` :::warning ❌ Nah, I'm not really a fan of `[]`, `''`, and `,`... ::: - ### Or, we can access each by their index ```javascript document.write(students[0] + ' '); document.write(students[1] + ' '); document.write(students[2] + ' '); document.write(students[3] + ' '); document.write(students[4] + ' '); document.write(students[5] + ' '); document.write(students[6] + ' '); > Wilson Angela Jessica Watson Holmes Ben Cindy ``` :::warning 😖 Looks great, but there are so many lines of code... ::: - ### Better, we can use a `for loop` to **loop** through the array. ```javascript for (let i = 0; i < students.length; i++) document.write(students[i] + ' '); > Wilson Angela Jessica Watson Holmes Ben Cindy ``` :::success 🙆‍♂️ Same result as previous one, but much concise code!!! ::: - ### Better yet, a `.forEach()` method is much more prefered. ```javascript students.forEach(stdnt => document.write(`${stdnt} `)); > Wilson Angela Jessica Watson Holmes Ben Cindy ``` :::danger 🥴 However, we won't cover array methods in this lesson. They will be covered in more advanced lessons later on. ::: ## Pre/Post-in/decrement - ### Shorthand ways to do simple operations. | Original Operation | Shorthand Way | |--------------------|---------------| | `x = x + y ` | `x += y ` | | `x = x - y ` | `x -= y ` | | `x = x * y ` | `x *= y ` | | `x = x / y ` | `x /= y ` | | `x = x % y ` | `x %= y ` | | `x = x ** y` | `x **= y` | - ### Even shorter ways to do `x += 1` and `x -= 1`. | Statement | Name | Description | |-----------|-------------------|---------------------------------------| | `++x` | Pre-increment | `x += 1` | | `x++` | Post-increment | `x += 1` **but after this statement** | | `--x` | Pre-decrement | `x -= 1` | | `x--` | Post-decrement | `x += 1` **but after this statement** | - ### Example ```javascript let i = 0; document.write(`i is now ${i++}<br>`); document.write(`i is now ${++i}<br>`); > i is now 0 > i is now 2 ``` ## Syntax Cheatsheet :::info - ### `while` ```javascript while (condition) { // if condition is true, // repeat to execute this block of code until it's false. } ``` - ### `do` ... `while` ```javascript do { // execute this block of code, and then check condition. // if it's true, repeat. } while (condition); ``` - ### `for` ```javascript // before the loop even starts, statement1 is executed. for (statement1; condition; statement2) { // if condition is true, // repeat to execute this block of code then statement2 // until it's false. } ``` ::: ## The `while` Loop > ### As we can see from its syntax, if `condition` is true,<br>we will keep repeating to run the code block.<br>Therefore, we need to find a way to **terminate the loop**. - ### We can use a simple expression to determine the loop condition. :::info For example, we know that the index of an array cannot exceed its length. ::: ```javascript let i = 0; while (i < students.length) { document.write(students[i] + ' '); i++; } ``` :::info For another example, let's say we're going to calculate the sum of all integers between 1 to 100 using `while`. We know that we want to stop at 100. ::: ```javascript= let sum, i; sum = 0; i = 1; while (i <= 100) { sum += i; ++i; } document.write(sum + '<br>'); ``` ## The `do while` Loop > ### The `condition` is evaluated at the end of each loop.<br>Simply put, the code block will be executed at least once REGARDLESS of the `condition`. - ### Why would we ever want to use `do while`?<br>Let's say we're counting how many digits there are in an integer. :::info A `while` loop seems nice and innocent, but if an user type in `0`, the output is incorrect. ::: ```javascript= let num = window.prompt("Enter an Integer: "); let n = num; let digit = 0; while (n > 0) { n = Math.floor(n / 10); digit++; } document.write(digit + '<br>'); ``` :::info A `do while` loop ensures that `digit` is at least incremented once.<br>Therefore, we don't get a wrong answer when entering `0`. ::: ```javascript= let num = window.prompt("Enter an Integer: "); let n = num; let digit = 0; do { n = Math.floor(n / 10); digit++; } while (n > 0); document.write(digit + '<br>'); ``` :::danger We must also be flexible and remember that there are always other ways to solve a problem. ::: - #### Solution 1: ```javascript= let num = window.prompt("Enter an Integer: "); let n = num; let digit = 1; while ((n = Math.floor(n / 10)) > 0) { digit++; } document.write(digit + '<br>'); ``` - #### Solution 2: ```javascript= let num = window.prompt("Enter an Integer: "); let n = num; digit = 1; if (num > 0) { digit = 0; while (n > 0) { n = Math.floor(n / 10); digit++; } } document.write(digit + '<br>'); ``` ## The `for` Loop > ### Although there are some minor differences,<br>the`for` loop is just a simplified version of the `while` loop. ### `for` syntax :::info ```javascript // before the loop even starts, statement1 is executed. for (statement1; condition; statement2) { // if condition is true, // repeat to execute this block of code then statement2 // until it's false. } ``` ::: ### The 3 Expressions in `for`'s Parentheses > ### All three expressions are **OPTIONAL**;<br>that is, you can write `for` like this `for( ; ; )`. - ### `statement1`: Initialization of the loop :::info Normally you will use `statement1` to initialize the variable used in the loop (`let i = 0`). ::: - ### `condition`: To loop or not to loop :::info Often `condition` is used to evaluate the condition of the initial variable. ::: :::danger Omission of `condition` creates a what's called an **"infinite loop"** which will be discussed in the next part. ::: - ### `statement2`: Prepareation for the next iteration :::info Often `statement2` increments the value of the initial variable. ::: ### Examples of `for` loops - ### Example 1 of `while` rewritten in `for` ```javascript for (let i = 0; i < students.length; ++i) document.write(students[i] + ' '); ``` - ### Example 2 of `while` rewritten in `for` ```javascript let sum = 0; for (let i = 0; i <= 100; ++i) sum += i; document.write(sum + '<br>'); ``` ## Fork this sheet I'm out! - ### **Infinite Loops** ```javascript while (1) { document.write('Dormammu, I\'ve come to bargain.<br>'); } ``` ```javascript for ( ; ; ) { document.write('Dormammu, I\'ve come to bargain.<br>'); } ``` ![](https://i.imgur.com/VwnlqZ1.jpg) - ### Give MCC a `break`! :::info `break` can be used to break out of exactly **ONE** loop.<br>It's good for an infinite loop. ::: ```javascript let i = 1; while (1) { document.write('Help me, step bro, I\'m stuck!<br>'); if (i++ == 69) break; } document.write('<br>You know the rules and so do I.<br>'); ``` - ### [Reference Video link](https://www.youtube.com/watch?v=dQw4w9WgXcQ) ![](https://i.imgur.com/aN2Dth5.jpg) - ### Let's `continue`, shall we? :::info `continue` skip the code all the way to **THE END OF THE LOOP**, not escape it. ::: ```javascript for (let i = 1; i <= 100; ++i) { if (i % 3 !== 0) continue; document.write(`${i} is a multiple of 3<br>`); } ``` ![](https://i.imgur.com/F2ZWu1T.jpg) --- # Exercise 2: The FizzBuzz Game ## Descrpition :::info Count incrementally to 100,<br>replacing any number divisible by 3 with the word `fizz`,<br>and any number divisible by 5 with the word `buzz`;<br>however, if a number is divisible by both 3 and 5, say `fizzbuzz`. ::: ## Sample output for the first 20 numbers ```= 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz ``` ## [Reference Answer](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/Exercises/ex2.js) - ### [`ex2.js`](https://github.com/qiyoudaoyi/822-web-course/blob/main/JS/Exercises/ex2.js) ```javascript= for (let i = 1; i <= 100; i++) { let str = ""; if (i % 3 === 0) str += "fizz"; if (i % 5 === 0) str += "buzz"; if (!str) str = i; console.log(str); } ``` --- # Lesson 6: Function Basics > ### A Function is a wrapper of code. > ### It can take in "parameters" and be executed (when called) accordingly. > ### Better yet, functions can return a value when finished. ## Let's first learn by some examples ### Example 1: Are you winning, son? ![](https://i.imgflip.com/4vthml.jpg) - ### A function with no parameters ```javascript= function DadSpeaks() { doucument.write("Are you winning, son?<br>"); } DadSpeaks(); ``` - ### A function that takes in the parameter ```javascript= function DadSpeaksTo(whom) { doucument.write(`Are you winning, ${whom}?<br>`); } DadSpeaksTo('Pewds'); ``` - ### A function that returns a value ```javascript= function DadSpeech(whom) { const speech = `Are you winning, ${whom}?<br>`; return speech; } document.write(DadSpeech('Pewds')); ``` ### Example 2: compute the surface and volume of a sphere given its radius - ### Supplement :::info - `.toFixed(digit)`: return a `string` representing the number. - `digit` (`0` by default) is the number of digits to appear after the decimal point. ::: - ### Not Using a function ```javascript= const pi = 3.1415926; const r1 = 5, r2 = 19; r3 = 37; // r1's surface and volume; let s1 = 4 * pi * r1**2; s1 = s1.toFixed(2); let v1 = 3/4 * pi * r1**3; v1 = v1.toFixed(2); console.log(`r1 = ${r1}, s1 = ${s1}, v1 = ${v1}<br>`); // r2's surface and volume; let s2 = 4 * pi * r2**2; s2 = s2.toFixed(2); let v2 = 3/4 * pi * r2**3; v2 = v2.toFixed(2); console.log(`r2 = ${r2}, s2 = ${s2}, v2 = ${v2}<br>`); // r3's surface and volume; let s3 = 4 * pi * r3**2; s3 = s3.toFixed(2); let v3 = 3/4 * pi * r3**3; v3 = v3.toFixed(2); console.log(`r3 = ${r3}, s3 = ${s3}, v3 = ${v3}<br>`); ``` - ### Using functions ```javascript= const pi = 3.1415926, r1 = 5, r2 = 19; r3 = 37; // Anonymous Funtions const Sur = r => (4 * pi * r**2).toFixed(2); const Vol = r => (3/4 * pi * r**3).toFixed(2); console.log(`r1 = ${r1}, s1 = ${Sur(r1)}, v1 = ${Vol(r1)}`); console.log(`r2 = ${r2}, s2 = ${Sur(r2)}, v2 = ${Vol(r2)}`); console.log(`r3 = ${r3}, s3 = ${Sur(r3)}, v3 = ${Vol(r3)}`); ``` ## Reference Video:<br>The Simplest Math Problem No One Can Solve - Collatz Conjecture {%youtube 094y1Z2wpJg %} > ### Let's now make a function `f(x) = 3x + 1` ## Function Declarations ### Normal Functions declared with names :::info ```javascript function f1(x) { const res = 3 * x + 1; return res; } ``` ::: ### Anonymous Function or Lambda Expression > ### Anonymous function (or lambda expression) is a function with no name. > ### There are two ways to create such things - ### Normal Approach :::info 1. ### Anonymous Note that this function will be gone after this line. ```javascript function(x) { const res = 3 * x + 1; return res; } ``` 1. ### You can give it a name by assigning it to a variable. ```javascript const f2 = function(x) { const res = 3 * x + 1; return res; } ``` ::: - ### Arrow function :::info 1. ### Anonymous ```javascript (x) => { const res = 3 * x + 1; return res; } ``` 1. ### Assigning it to a variable to retain it. ```javascript const f3 = (x) => { const res = 3 * x + 1; return res; } ``` 1. ### You can omit the parentheses when there's only one parameter. ```javascript const f4 = x => { return 3 * x + 1; } ``` 1. ### If the function has only one `return` statement,<br>the brackets and `return` are not needed. ```javascript const f5 = x => 3 * x + 1; ``` - ### Looks cool, so what's the difference? ![](https://i.imgur.com/J5zHU24.jpg) ## Calling Funtions > ### `()` along with the indicated parameters calls the functuon. ```javascript= function f1(x) { const res = 3 * x + 1; return res; } const f5 = x => 3 * x + 1; const Hi2 = () => { document.write(`Hi!<br>`); document.write(`Hi again!<br>`); } document.write(f1(4) + '<br>'); document.write(f5(28) + '<br>'); Hi2(); ``` ## Recursive Functions > ### A function this calls itself is a recursive function. ```javascript= const Factorial = n => { if (n === 1) return 1; return n * Factorial(n - 1); } console.log(Factorial(5)); > 120 ``` ## Callback Function > ### But here's a `function`, so call me **MAYBE**. > {%youtube fWNaR-rxAic%} > > ### A function that is passed into another function as an argument is a callback function. - ### `setTimeout` is a function that takes in another function ```javascript= setTimeout(() => { console.log("One second has passed!!!"); }, 1000); ``` :::info ### We will be discussing a lot of callback functions later on the course. ::: --- # Lesson 7: Objects and Classes ## Objects :::danger ### **Everything** in JavaScript is and work as **an object**. ::: > ### JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is just a `key-value` pair.<br>This kind of programming paradigm is also known as `Object-oriented Programming` or `OOP` for short. ### Object Declaration ```javascript= const person = { fName : 'Wilson', lName : 'Chang', age : 20, job : ['student', 'tutor'], }; ``` ### Object Properties or Key-value Pairs - ### A `key` is a string (normally a name for the value).<br>A `value` can be of any type in JavaScript. | Key | Value |type| |--------|-----------------|------| | `fName` | `Wilson `|`string`| | `lName` | `Chang `|`string`| | `age` | `20 `|`number`| | `job` | `student, tutor `|`array` | - ### Strings and Arrays are also objects with key-value pairs - ### `const str = "Wilson";` |key |`0`|`1`|`2`|`3`|`4`|`5`| |---------|---|---|---|---|---|---| |**value**|`W`|`i`|`l`|`s`|`o`|`n`| - ### `const arr = ["apple", "banana", "orange"];` |key |`0` |`1` |`2` | |---------|---------|----------|----------| |**value**|`"apple"`|`"banana"`|`"orange"`| ### Accessing Properties - ### Use the `.` operator ```javascript console.log(person.fName); > Wilson ``` - ### Access `Value` via `Key` ```javascript console.log(person['fName']); > Wilson ``` ### Object within a Object ```javascript= const person = { fName : 'Wilson', lName : 'Chang', age : 20, job : ['student', 'tutor'], friend: [{ fName : 'Peter', lName : 'Parker', age : 19, job : ['Avengers', 'reporter', 'student'], }, { fName : 'Dio', lName : 'Brando', age : 150, job : 'philosopher', stand : 'Za Warudo' }], }; ``` ### Object Methods > ### `Method` is just a function inside an `object` or a `class`. ```javascript= const person = { fName : 'Wilson', lName : 'Chang', age : 20, job : ['student', 'tutor'], fullName: function() { return `${this.fName} ${this.lName}`; } }; console.log(person.fullName()); ``` ``` > Wilson Chang ``` :::danger ### Always use normal funtions when creating methods. ::: ### Okay, but what is `this`? > ### `this` is a reference to the `object` in current execution context. > ### However, a `function` redefines its `this` to its belonging scope <br>while an `arrow function` doesn't. :::info ### Simply put, `this` in JavaScript works very differently than in other languages.<br>However, as for the time being, we won't be using `this` that much, so you can just learn `this` as we go. ::: ```javascript= const person = { // person is a NEW SCOPE fName : 'Wilson', lName : 'Chang', age : 20, job : ['student', 'tutor'], whats_this1: function() { // binds this to the NEW SCOPE return this; }, whats_this2: () => this, // this is still Window }; console.log(this); console.log(person.whats_this1()); console.log(person.whats_this2()); ``` ``` > Window {window: Window, self: Window, document: document, name: '', location: Location, …} > {fName: 'Wilson', lName: 'Chang', age: 20, job: Array(2), whats_this1: ƒ, …} > Window {window: Window, self: Window, document: document, name: '', location: Location, …} ``` ## JSON (JavaScript Object Notation) > ### JSON is statically indentical to `objects` that we just learned.<br>Just remember that every `string`, including `keys` in JSON has to be wrapped in double quotes. - ### An **super-simplified** example of JSON ```json= [ { "name" : "Molecule Man", "age" : 29, "secretIdentity" : "Dan Jukes", "powers" : [ "Radiation resistance", "Turning tiny", "Radiation blast" ] }, { "name" : "Madame Uppercut", "age" : 39, "secretIdentity" : "Jane Wilson", "powers" : [ "Million tonne punch", "Damage resistance", "Superhuman reflexes" ] } ] ``` - ### An in-real-life JSON from IMBd ```json= {"searchType":"Title","expression":"violet evergarden","results":[{"id":"tt7078180","resultType":"Title","image":"https://imdb-api.com/images/original/MV5BZmUzMThjOTItZGY4ZS00ODcwLTliNTMtYjVkM2JmY2QxNmRhXkEyXkFqcGdeQXVyMzgxODM4NjM@._V1_Ratio0.7273_AL_.jpg","title":"Violet Evergarden","description":"(2018) (TV Mini Series)"},{"id":"tt8652818","resultType":"Title","image":"https://imdb-api.com/images/original/MV5BYTJmNzc5YTEtNTBmNy00YmUxLWFlNzktYjZjMTg3OGY3ZDhkXkEyXkFqcGdeQXVyMzUzMzgxNA@@._V1_Ratio0.7273_AL_.jpg","title":"Violet Evergarden: The Movie","description":"(2020)"},{"id":"tt10477558","resultType":"Title","image":"https://imdb-api.com/images/original/MV5BZjljM2M1ZTgtZGM4My00OGRkLTliMjAtYzJiZDBkMzQ5ZDkzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_Ratio0.7273_AL_.jpg","title":"Violet Evergarden: Eternity and the Auto Memories Doll","description":"(2019)"}],"errorMessage":""} ``` - ### After handling that mess of data ```json= [{ "id":"tt7078180", "resultType":"Title", "image":"https://imdb-api.com/images/original/MV5BZmUzMThjOTItZGY4ZS00ODcwLTliNTMtYjVkM2JmY2QxNmRhXkEyXkFqcGdeQXVyMzgxODM4NjM@._V1_Ratio0.7273_AL_.jpg", "title":"Violet Evergarden", "description":"(2018) (TV Mini Series)" }, { "id":"tt8652818", "resultType":"Title", "image":"https://imdb-api.com/images/original/MV5BYTJmNzc5YTEtNTBmNy00YmUxLWFlNzktYjZjMTg3OGY3ZDhkXkEyXkFqcGdeQXVyMzUzMzgxNA@@._V1_Ratio0.7273_AL_.jpg", "title":"Violet Evergarden: The Movie", "description":"(2020)" },{ "id":"tt10477558", "resultType":"Title", "image":"https://imdb-api.com/images/original/MV5BZjljM2M1ZTgtZGM4My00OGRkLTliMjAtYzJiZDBkMzQ5ZDkzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_Ratio0.7273_AL_.jpg", "title":"Violet Evergarden: Eternity and the Auto Memories Doll", "description":"(2019)" }] ``` - ### Yeah that's cool, but how can we put it into use? - ### Introducing `Fetch API` > Don't worry, I'm not teaching this yet. The code below is just a demonstration of how data can be manipulated via JavaScript. :::info ### We often use `Fetch API` to `GET` data on the Internet and also use it to `POST` information of our own onto the web. ::: ```javascript= const ibmdDiv = document.getElementById("imbd"); fetch("https://imdb-api.com/en/API/Search/k_sutkxi5l/violet evergarden") .then(res => res.json()) .then(data => { console.log(data); data.results.forEach(datum => { wrapper = document.createElement("div"); title = document.createElement("h3"); title.innerHTML = datum.title; poster = document.createElement("img"); poster.src = datum.image; poster.width = "768"; wrapper.append(title); wrapper.append(poster); ibmdDiv.append(wrapper); }) }) .catch(err => { console.log(err); }); ``` ## Classes > ### We've learnt `object`, and `class` is just a **blueprint** for `object`. > ### In another word, `class` allows us to create `object` of the same kind very quickly. ### Learn to use `class` in just 5 mins. - ### Crate a class called `Person` ```javascript= class Person { constructor(fn, ln, a) { this.fname = fn; this.lname = ln; this.age = a; } get fullName() { return this.fname + ' ' + this.lname; } greeting() { return `Hi, I'm ${this.fullName}, and I'm ${this.age} years old.` } } ``` :::info - ### Add `()` to create `class methods` - ### `get` allows us to treat `methods` as if they were `properties`. ::: - ### Use `new` to create an `object` via `class` ```javascript const p1 = new Person('Wilson', 'Chang', 20); const p2 = new Person('Peter', 'Parker', 19); console.log(p1); console.log(p1.fullName); console.log(p1.greeting()); console.log(p2); console.log(p2.fullName); console.log(p2.greeting()); ``` ``` > person { fname: 'Wilson', lname: 'Chang', age: 20 } > Wilson Chang > Hi, I'm Wilson Chang, and I'm 20 years old. > person { fname: 'Peter', lname: 'Parker', age: 19 } > Peter Parker > Hi, I'm Peter Parker, and I'm 19 years old. ``` ### Supplement: `class inheritance` - ### `extends` preserves all methods from the extended class (or parent class). ```javascript= class EEstudent extends Person { constructor(fn, ln, a, c) { super(fn, ln, a) this.credit = c; } greeting() { return `I'm an EE student and I have ${this.credit} credits this semester.`; } whining() { return 'Sinals and Systems is so hard...'; } } const p3 = new EEstudent('Wilson', 'Chang', 20, 23); console.log(p3); console.log(p3.fullName) console.log(p3.greeting()); console.log(p3.whining()); ``` ``` > EEstudent { fname: 'Wilson', lname: 'Chang', age: 20, credit: 23 } > Wilson Chang > I'm an EE student and I have 23 credits this semester. > Sinals and Systems is so hard... ``` :::info - ### `super()` is reference to the parent class. - ### Note that we can also rewrite methods form the parent class. ::: --- # Lesson 8: Arrays Methods ## Reference Arrays ```javascript const myNums = [4, 6, 7, 23, 45, 50, 69, 100]; ``` ## Normal `for` review ```javascript let forSquares = []; for (let i = 0; i < myNums.length; i++) forSquares.push(myNums[i]**2); console.log("Normal for loop:", forSquares); ``` ## `for in`, `for of`, and `forEach` - ### `for in`: loop over **KEYS** ```javascript let forinSquares = []; for (let key in myNums) forinSquares.push(myNums[key]**2); console.log("for in:", forinSquares); ``` - ### `for of`: loop over **VALUES** ```javascript let forofSquares = []; for (let value of myNums) forofSquares.push(value**2); console.log("for of:", forofSquares); ``` - ### `forEach` :::info ### The callback funtion in `forEach` can take in up to 3 arguments: ### `function(value, key, original_array) {...}` ::: ```javascript let forEachSquares = []; myNums.forEach(myNum => { forEachSquares.push(myNum**2); }); console.log("forEach method:", forEachSquares); ``` ## `map`, `filter`, and `reduce` :::info ### The callback funtions in all three functions works like that in `forEach`: ### `function(value, key, original_array) {...}` ::: - ### `map` ```javascript const mapSquares = myNums.map(myNum => myNum**2); console.log("map method:", mapSquares); ``` - ### `filter` ```javascript const filteredNums = myNums.filter(myNum => myNum > 40); console.log("Filter out numbers that is <= 40:", filteredNums); ``` - ### `reduce` ```javascript const Sum = myNums.reduce((acc, curNum) => acc + curNum, 0) console.log("Sum:", Sum); ``` ##