1212
added fundamental for scope · nudge/JavaScript2@e93b400 · GitHub
Skip to content

Commit e93b400

Browse files
committed
added fundamental for scope
1 parent 1e466d2 commit e93b400

File tree

3 files changed

+121
-2
lines changed

3 files changed

+121
-2
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Here you can find course content and homework for the JavaScript 1,2 and 3 modul
99
|0.|Preparation for your first JavaScript session|[Pre-reading](/Week0/README.md)|-|
1010
|1.|Git Session with Unmesh|[Reading Week 1](/Week1/README.md) | [Homework Week 1](/Week1/MAKEME.md)|
1111
|2.|• Intro JavaScript (What is it, where can you use it for)<br>• [Variables (var, let, const)](fundamentals/variables.md)<br>• [Basic Data types (strings, numbers, arrays, booleans)](fundamentals/values.md)<br>• [Operators](fundamentals/operators.md)<br>• [Naming conventions](fundamentals/naming_conventions.md)|[Reading Week 2](/Week2/README.md)|[Homework Week 2](/Week2/MAKEME.md)|
12-
|3.|• Git work flow :smiling_imp:<br>• [Advanced data types (objects)](fundamentals/objects.md) <br>• [Conditional execution](fundamentals/conditional_execution.md) <br>• [Statements vs Expressions](fundamentals/statements_expressions.md)<br> • [Loops (for/while)](fundamentals/loops.md)<br>• [Functions](fundamentals/functions.md) <br>• Scope|[Reading Week 3](/Week3/README.md)|[Homework Week 3](/Week3/MAKEME.md)|
12+
|3.|• Git work flow :smiling_imp:<br>• [Advanced data types (objects)](fundamentals/objects.md) <br>• [Conditional execution](fundamentals/conditional_execution.md) <br>• [Statements vs Expressions](fundamentals/statements_expressions.md)<br> • [Loops (for/while)](fundamentals/loops.md)<br>• [Functions](fundamentals/functions.md) <br>• [Scope](fundamentals/scope.md)|[Reading Week 3](/Week3/README.md)|[Homework Week 3](/Week3/MAKEME.md)|
1313
|4.|• Capturing user input <br>• Events<br>• [Basic DOM manipulations (img src, innerHTML)](fundamentals/DOM_manipulation.md)<br>• Code debugging using the browser <br>• [Code commenting](fundamentals/code_commenting.md)<br>• Structuring code files |[Reading Week 4](/Week4/README.md)|[Homework Week 4](/Week4/MAKEME.md)|
1414
|5.|• Functions + JSON/Arrays<br>• [Array Manipulations](fundamentals/array_manipulation.md)<br>• JSON<br>• [Map and filter](fundamentals/map_filter.md)<br>• Arrow functions |[Reading Week 5](/Week5/README.md)|[Homework Week 5](/Week5/MAKEME.md)|
1515
|6.|[Closures](fundamentals/scope_closures_this.md) <br>• Callbacks|[Reading Week 6](/Week6/README.md)|[Homework Week 6](/Week6/MAKEME.md)|

Week3/MAKEME.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Provide feedback to the homework of last week to one of your fellow students. Yo
3535
- [Statements vs Expressions](../fundamentals/statements_expressions.md)
3636
- [Loops (for/while)](../fundamentals/loops.md)
3737
- [Functions](../fundamentals/functions.md)
38-
- Scope
38+
- [Scope](../fundamentals/scope.md)
3939

4040
## Step 2: Watch
4141

fundamentals/scope.md

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Scope
2+
3+
## What is scope?
4+
5+
Definition from [Dictionary.com](http://www.dictionary.com/browse/scope):
6+
7+
> noun
8+
1\. extent or range of view, outlook, application, operation, effectiveness, etc.:
9+
10+
If you imagine yourself as the computer that is executing your JavaScript code, you can think of scope as meaning:
11+
12+
> what you can see from where your are
13+
14+
In this case the 'things' that you are looking for are variables and functions. When we say, "What's in scope?", we mean "Which variables and functions can be accessed from the current point of execution in your code?" As it happens, in JavaScript there are three types of scope to consider.
15+
16+
## Global scope
17+
18+
Variables and functions defined at global scope are visible from any point of execution in your code. Sometimes that's a good thing (or even essential), but more often it's bad. Let's dive right in.
19+
20+
```js
21+
a = 10; // don't do this
22+
console.log(a);
23+
```
24+
25+
In this example we have assigned the value `10` to a variable that we forgot to declare (we forgot to use `let`, `const` or `var`). The JavaScript engine tries to be helpful and defines a variable `a` for us in **global** scope. More recently, the JavaScript community considered this friendliness to be an error and with ES5 instroduced `strict` mode: place the string `'use strict';` at the top of your file.
26+
27+
```js
28+
'use strict';
29+
a = 10; // produces: ReferenceError: a is not defined
30+
console.log(a);
31+
```
32+
33+
You can correct this by declaring your variable with `var`:
34+
35+
```js
36+
'use strict';
37+
var a = 10;
38+
console.log(a);
39+
```
40+
41+
This still puts the variable `a` into the global scope. So why is global scope a problem? Because you cannot be sure that the variable names you choose do not conflict with names already present in global scope (global scope is a busy place). It is best to apply the principle of 'need to know'. Only expose your variables to other parts in the JavaScript ecosystem that need to know about them. This is where local scope and block scope come in.
42+
43+
## Local scope
44+
45+
When you declare a function in JavaScript the function body represents a new, local scope, distinct from global scope. Variables defined in the function body are visible only inside that function: from the outside, you can't look in.
46+
47+
```js
48+
'use strict';
49+
50+
function myFunction() {
51+
const a = 10;
52+
console.log(a);
53+
}
54+
55+
myFunction();
56+
57+
// console.log(a); <= this would produce: ReferenceError: a is not defined
58+
```
59+
60+
But from the inside you can look out. In the example below the variable `b` is visible from inside the function body.
61+
62+
```js
63+
'use strict';
64+
65+
const b = 'Hello';
66+
67+
function myFunction() {
68+
const a = 10;
69+
console.log(a);
70+
console.log(b);
71+
}
72+
73+
myFunction();
74+
```
75+
76+
You might think that the variable `b` is in global scope. Actually, variables declared with either `let` or `const` have block scope, as will be discussed next. Note however that the function `myFunction` still resides in global scope. There is a way to even get `myFunction` out of global scope by using, what is called, an **IIFE**. See further down below.
77+
78+
## Block scope
79+
80+
The keywords `let` and `const` were introduced in ES6 as alternative to the older `var` keyword and we recommend that you use these newer keywords instead of `var`. They adhere to the rules for block scope, whereas `var` is completely oblivious of the concept.
81+
82+
A new block scope (sometimes called _lexical_ scope) is created whenever you create a block of code inside a pair of curly braces. Variables defined with `let` and `const` at the file level (i.e., not inside a function) are considered to be in a (file-level) block scope. That's why the varable `b` in the previous code snippet is not in global scope. Had we replaced `const b` with `var b` then variable `b` _would be_ in global scope.
83+
84+
## Guidance
85+
86+
Following the principle of 'need to know', it is best to define variables at the point of need, i.e. just before you need to access these variables. This will either be in the same scope of the code where you access the variable, or, in case you need to access the variable from multiple places, the closest scope that is common to the points of need.
87+
88+
Sometimes however, you cannot avoid global scope. This is for instance the case when you want to access the [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) in the browser. As you will learn, you can create an HTML element (e.g. an `h1` element) in JavaScript using this code:
89+
90+
```js
91+
const h1 = document.createElement('h1');
92+
```
93+
94+
The `document` object resides in global scope, conveniently provided there by the browser for access by any piece of JavaScript that needs to manipulate the DOM.
95+
96+
## IFFE
97+
98+
We were left with the issue that functions defined at the file level still end up in global scope. The traditional method of solving this in JavaScript is to use an Immediately Invoked Function Expression (IIFE). We present it here for info. When you build web applications with modern tools such as React and Node, you do not need to use IFFEs.
99+
100+
To use an IFFE you must wrap all of your JavaScript code in a function body of an anonymous function (i.e., a function with no name) and immediately call that function (as indicated by the empty set of parentheses on the last line). This creates a local scope for your code. Now even the `myFunction` function is in local scope.
101+
102+
```js
103+
(function () {
104+
'use strict';
105+
106+
const b = 'Hello';
107+
108+
function myFunction() {
109+
const a = 10;
110+
console.log(a);
111+
console.log(b);
112+
}
113+
114+
myFunction();
115+
})();
116+
```
117+
118+
More info on MDN: [IFFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
119+

0 commit comments

Comments
 (0)