|
| 1 | +## Variables and statements |
| 2 | + |
| 3 | +Semicolons used to end a statement. You can choose to not write them _(because there is ASI: Automatic Semicolon Insertion in Javascript)_. |
| 4 | + |
| 5 | +### Declaring a variable: |
| 6 | + |
| 7 | +`var first = 'Soumya';` |
| 8 | + |
| 9 | +`let first = 'Soumya';` |
| 10 | + |
| 11 | +`const first = 'Soumya';` |
| 12 | + |
| 13 | +(here value is 'Soumya') |
| 14 | + |
| 15 | +- `let` and `const` were introduced in ES6 (newer). |
| 16 | + |
| 17 | +- `var` and `let` can be updated but not `const`. |
| 18 | + |
| 19 | + ```javascript |
| 20 | + var x = 'hey'; |
| 21 | + y = 'hi'; |
| 22 | + |
| 23 | + let cool = true; |
| 24 | + cool = false; |
| 25 | + |
| 26 | + const age = 10; |
| 27 | + age = 11; // wrong: throws error |
| 28 | + |
| 29 | + ``` |
| 30 | + |
| 31 | +- In **strict mode**, we have to define a variable first before assigning a value to it. |
| 32 | + |
| 33 | + ```javascript |
| 34 | + dog = 'snickers'; // bad coding, don't do this |
| 35 | + console.log(dog); // snickers (no error) |
| 36 | + |
| 37 | + 'use strict'; |
| 38 | + dog = 'snickers'; // error: dog is not defined |
| 39 | + |
| 40 | + ``` |
| 41 | + |
| 42 | +- If we write `var dog;` dog is _undefined._ |
| 43 | + |
| 44 | +- **Scoping:** |
| 45 | + |
| 46 | + - **var** : _function scoped_ (only available inside parent functions) |
| 47 | + |
| 48 | + - **let** and **const** : _block scoped_ (available inside a block denoted by _{ }_ ) |
| 49 | + |
| 50 | +- **Opinion (what to use):** Use `const` by default; if the value of the variable needs to change then use `let`. Almost never use `var`. |
| 51 | + |
| 52 | +- **Variable naming conventions:** |
| 53 | + |
| 54 | + - Should not start with capital unless they are a _class_. |
| 55 | + - Must start with **a-z** or **_** or **$**. |
| 56 | + - If a variable is multi-word, you can use: |
| 57 | + - _Camel-case:_ `let iLovePizza = true;` |
| 58 | + - _Upper Camel case (in case of classes):_ `ILovePizza` |
| 59 | + - _Snake case: `let i_love_pizza=true;`_ |
0 commit comments