|
| 1 | +# Control Structures (if..else Statements, Loops & Error Handling) |
| 2 | + |
| 3 | +| Contents | |
| 4 | +| :--- | |
| 5 | +| [Conditional Statements - if, if...else & if...else if...else](#conditional-statements---if-ifelse--ifelse-ifelse) | |
| 6 | +| [Loops in JS](#loops-in-js) | |
| 7 | +| [Error Handling with "try-catch"](#error-handling-with-try-catch) | |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +:abacus: [Understand with Code](summary-with-code/script.js) |
| 12 | + |
| 13 | +:notebook_with_decorative_cover: [Projects](projects/) |
| 14 | + |
| 15 | +## Conditional Statements - if, if...else & if...else if...else |
| 16 | + |
| 17 | +Always keep in mind that `condition` in |
| 18 | + |
| 19 | +``` |
| 20 | +if (condition) { ... } |
| 21 | +``` |
| 22 | + |
| 23 | +simply has to be a **boolean value**. |
| 24 | + |
| 25 | +Often, you'll generate such a boolean value with the help of `===`, `>`, `<` etc. All these operators yield boolean values (without changing the variables/values you're using them on). |
| 26 | + |
| 27 | +Since `if` only wants a boolean, you of course **don't have to use such an operator**. If you already got a variable that holds a boolean, you can use it without any extra operator. |
| 28 | + |
| 29 | +Example: |
| 30 | + |
| 31 | +``` |
| 32 | +const isLoggedIn = true; |
| 33 | +if (isLoggedIn) { |
| 34 | + // This code will execute because isLoggedIn is true => A valid condition |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +You could write |
| 39 | + |
| 40 | +``` |
| 41 | +const isLoggedIn = true; |
| 42 | +if (isLoggedIn === true) { |
| 43 | + ... |
| 44 | +} |
| 45 | +``` |
| 46 | +but that would be redundant. You'd generate another new boolean where you already got one. |
| 47 | + |
| 48 | +You can use the ! operator to negate ("invert") the value: |
| 49 | + |
| 50 | +``` |
| 51 | +const isLoggedIn = true; |
| 52 | +if (!isLoggedIn) { |
| 53 | + // This code will NOT execute because isLoggedIn is true but ! inverts it (in this check) |
| 54 | +} else { |
| 55 | + // This would execute because !isLoggedIn yields false => else block executes |
| 56 | +} |
| 57 | +``` |
| 58 | +Again, that would be similar to: |
| 59 | + |
| 60 | +``` |
| 61 | +const isLoggedIn = true; |
| 62 | +if (isLoggedIn !== true) { |
| 63 | + // This would NOT execute |
| 64 | +} else { |
| 65 | + // This would execute because isLoggedIn is true and hence !== true yields false |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +But again, that would be redundant. |
| 70 | + |
| 71 | +### [Falsy & Truthy Values](https://drive.google.com/uc?export=view&id=19VJ__vz6UQcPxO64cqkJvQ4DTcoqEaDr) |
| 72 | + |
| 73 | +It's important to understand that JavaScript is able to use variables in conditions, even without comparison operators. |
| 74 | + |
| 75 | +This is kind of obvious, if we consider a boolean variable, for example: |
| 76 | + |
| 77 | +``` |
| 78 | +let isLoggedIn = true; |
| 79 | +if (isLoggedIn) { |
| 80 | + ... |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +Since if just wants a condition that returns true or false, it makes sense that you can just provide a boolean variable or value and it works without the extra comparison (`if (isLoggedIn === true)`, that would also work but is redundant). |
| 85 | + |
| 86 | +Whilst the above example makes sense, it can be confusing when you encounter code like this for the first time: |
| 87 | + |
| 88 | +``` |
| 89 | +let userInput = 'Max'; |
| 90 | +if (userInput) { |
| 91 | + ... // this code here will execute because 'Max' is "truthy" (all strings but empty strings are) |
| 92 | +} |
| 93 | +``` |
| 94 | + |
| 95 | +***JavaScript tries to coerce ("convert without really converting") the values you pass to `if` (or other places where conditions are required) to boolean values.*** |
| 96 | + |
| 97 | +That means that it tries to interpret `'Max'` as a boolean and there it follows the rules which is `0` is treated as false, all other numbers are treated as true etc. |
| 98 | + |
| 99 | +It's important to understand that JavaScript doesn't really convert the value though. |
| 100 | + |
| 101 | +`userInput` still holds `'Max'` after being used in a condition like shown above - it's not converted to a boolean. That would be horrible because you'd invisibly lose the values stored in your variables. |
| 102 | + |
| 103 | +Instead, |
| 104 | + |
| 105 | +``` |
| 106 | +if (userInput) { ... } |
| 107 | +``` |
| 108 | + |
| 109 | +is basically transformed (behind the scenes) to |
| 110 | + |
| 111 | +``` |
| 112 | +if (userInput === true) { |
| 113 | +``` |
| 114 | + |
| 115 | +And here, the `=== operator` generates and returns a boolean. It also doesn't touch the variable you're comparing, `userInput` stays a string. But it generates a new boolean which is temporarily used in the comparison. |
| 116 | + |
| 117 | +And that's exactly what JavaScript automatically does when it finds something like this: |
| 118 | + |
| 119 | +``` |
| 120 | +if (userInput) { ... } |
| 121 | +``` |
| 122 | + |
| 123 | +### [Ternary Operators/Conditional Expressions](https://drive.google.com/uc?export=view&id=1XL8s7xPM1w5Honj2TfCdaljEbDHdIVqD) |
| 124 | + |
| 125 | +***[Click Here](https://drive.google.com/uc?export=view&id=1vIjIWjVCoshekcTHqsbIft6AmI_Xs6aM) to know about logical operator tricks.*** |
| 126 | + |
| 127 | +``` |
| 128 | +const userName = 'Max'; |
| 129 | +const altName = ''; |
| 130 | +console.log(userName === 'Max'); // generates and prints a boolean => true |
| 131 | +console.log(userName); // wasn't touched, still is a string => 'Max' |
| 132 | + |
| 133 | +console.log(userName || null); // userName is truthy and therefore returned by || => 'Max' |
| 134 | +console.log(altName || 'Max'); // altName is falsy (empty string), hence 'Max' is returned => 'Max' |
| 135 | +console.log(altName || ''); // both altName and '' are falsy but if the first operand is falsy, the second one is always returned => '' |
| 136 | +console.log(altName || null || 'Anna'); // altName and null are falsy, 'Anna' is returned => 'Anna' |
| 137 | + |
| 138 | +console.log(userName && 'Anna'); // userName is truthy, hence second (!) value is returned => 'Anna' |
| 139 | +console.log(altName && 'Anna'); // altName is falsy, hence first value is returned => '' |
| 140 | +console.log(userName && ''); // userName is truthy, hence second value is returned => '' |
| 141 | +``` |
| 142 | + |
| 143 | +**Always keep in mind, NO operator** (neither `===`, `>` etc. nor `&&` or `||`) changes the variable you might be using in the comparison. In the above examples, the values stored in userName and altName are NEVER changed. |
| 144 | + |
| 145 | +`===`, `>` etc. just **generate new boolean values** which are used in the comparison. `||` and `&&` **generate NO booleans**, they just treat the **values before and after them as conditions** (which therefore need to yield boolean values and are coerced to booleans if required). |
| 146 | + |
| 147 | +Because of the above described behaviors, you often use `||` in JavaScript to assign default/fallback values to variables or constants: |
| 148 | + |
| 149 | +``` |
| 150 | +const enteredValue = ''; // let's assume this is set based on some input provided by the user, therefore it might be an empty string |
| 151 | + |
| 152 | +const userName = enteredValue || 'PLACEHOLDER'; // will assign 'PLACEHOLDER' if enteredValue is an empty string |
| 153 | +``` |
| 154 | + |
| 155 | +Readings: |
| 156 | + |
| 157 | +- [Making decisions in your code — conditionals](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals) |
| 158 | + |
| 159 | +- [JS Conditional Statements](https://www.freecodecamp.org/news/javascript-if-else-and-if-then-js-conditional-statements/) |
| 160 | + |
| 161 | +- [JavaScript if...else Statement](https://www.programiz.com/javascript/if-else) |
| 162 | + |
| 163 | +- [Conditional (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) |
| 164 | + |
| 165 | +- [JavaScript Ternary Operator](https://www.programiz.com/javascript/ternary-operator) |
| 166 | + |
| 167 | +- [2ality – JavaScript and more](https://2ality.com/2012/09/expressions-vs-statements.html) |
| 168 | + |
| 169 | +- [Switch Case in JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) |
| 170 | + |
| 171 | +- [JavaScript Switch Case – JS Switch Statement Example](https://www.freecodecamp.org/news/javascript-switch-case-js-switch-statement-example/) |
| 172 | + |
| 173 | +## [Loops in JS](https://drive.google.com/uc?export=view&id=1vi7o5Gb2aXUHH91UqtbgQUoBJFZSiLLo) |
| 174 | + |
| 175 | +| for loop | for-of loop | for-in loop | while loop | |
| 176 | +| :--- | :--- | :--- | :--- | |
| 177 | +| Execute code a certain amount of times (with counter variable) | Execute for every element in an array | Execute for every key in an object | Execute code as long as a condition is true | |
| 178 | +|<pre>for(let i=0; i < 3; i++) {<br/> console.log(i)<br/>}</pre>|<pre>for (const el of array) {<br/> console.log(el)<br/>}</pre>|<pre>for (const key in obj) {<br/> console.log(key, obj[key]);<br/>} </pre>|<pre>while(isLoggedIn) {<br/> ...<br/>} </pre>| |
| 179 | + |
| 180 | +Readings: |
| 181 | + |
| 182 | +- [JavaScript Loops Explained](https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/) |
| 183 | + |
| 184 | +- [How to Use Break & Continue Statements in JavaScript](https://javascript.plainenglish.io/hot-to-use-break-continue-statements-in-javascript-9b6d30e56deb) |
| 185 | + |
| 186 | +- [Label Statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label) |
| 187 | + |
| 188 | +## [Error Handling with "try-catch"](https://drive.google.com/uc?export=view&id=1_rqoo-T7NPfZPsU6Dc1qofa4j4g3bBtP) |
| 189 | + |
| 190 | +Readings: |
| 191 | + |
| 192 | +- [Error handling, "try...catch"](https://javascript.info/try-catch) |
| 193 | + |
| 194 | +- [JavaScript try...catch...finally Statement](https://www.programiz.com/javascript/try-catch-finally) |
| 195 | + |
| 196 | +- [JavaScript throw Statement](https://www.programiz.com/javascript/throw) |
0 commit comments