|
1 | | -# js-coding-samples |
2 | | -Javascript coding examples. |
| 1 | +# Javascript Code samples |
| 2 | + |
| 3 | +## Variable scope |
| 4 | + |
| 5 | +### Global scope |
| 6 | +A variable declared outside of all the function or without a `var` keyword is a global variable in Javascript. This variable can be accessed from anywhere in the program. |
| 7 | + |
| 8 | +``` |
| 9 | +// global scope |
| 10 | +var a = 1; |
| 11 | +b = 2; |
| 12 | + |
| 13 | +function one() { |
| 14 | + alert(a); // alerts '1' |
| 15 | + alert(b); // alerts '2' |
| 16 | +} |
| 17 | +``` |
| 18 | +If you use a `this` keyword outside an object, it resolves to `window` object which is a global object in Javascript. |
| 19 | +``` |
| 20 | +// global scope |
| 21 | +this.a = 1; |
| 22 | +b = 2; |
| 23 | +console.log(this.a); // 1 |
| 24 | +console.log(window.a); // 1 |
| 25 | +console.log(window.b); // 2 |
| 26 | +``` |
| 27 | +### Local scope |
| 28 | +If the variable is declared inside a function it takes the functions as its scope. This variable can be accessed within the function and not from outside the function. |
| 29 | +``` |
| 30 | +// global scope |
| 31 | +var a = 1; |
| 32 | + |
| 33 | +function one() { |
| 34 | + // local scope |
| 35 | + var a = 2; |
| 36 | + alert(a); // alerts '2' |
| 37 | +} |
| 38 | +alert(a); // alerts '1' |
| 39 | +``` |
| 40 | +If you omit the `var` keyword wihtin the function it is declared as a global variable. |
| 41 | +``` |
| 42 | +function one() { |
| 43 | + // not local but global, |
| 44 | + a = 2; |
| 45 | + alert(a); // alerts '2' |
| 46 | +} |
| 47 | +one(); |
| 48 | +alert(a); // alerts '2' |
| 49 | +``` |
| 50 | +If a variable resolved in a local scope, it will not check upwards towards global scope. For example, if the function `one` has a variable `a` declared it will take precedence over the global scope within the function. |
| 51 | +### Block scope |
| 52 | +ES6 introduced `let` and `const` which declares variables known only to the _enclosing_ parenthesis `{}`. For example, `for` loop or `if` condition. |
| 53 | +``` |
| 54 | +for (let i = 0; i < 10; i++) { |
| 55 | + console.log(i); |
| 56 | +} |
| 57 | +console.log(i); // undefined |
| 58 | +``` |
| 59 | +### Catch clause Scope |
| 60 | +There is also one special scope in Javascript which like `let`. It is the variable in the `catch` clause. This shodows other global and local variables in the same name, but only available within the `catch` block. |
| 61 | +``` |
| 62 | +try { |
| 63 | + throw 10; |
| 64 | +} catch(e) { |
| 65 | + console.log(e); // 10 |
| 66 | +} |
| 67 | +console.log(e) // Uncaught ReferenceError: e is not defined |
| 68 | +``` |
0 commit comments