You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: VSCodeTips/README.md
+1-7Lines changed: 1 addition & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -1,12 +1,6 @@
1
1
# VSCode Tips
2
2
3
-
Although you are free to make you own choice of text/code editor to use during class and homework, we have good experiences with Microsoft's free Visual Studio Code (VSCode) editor.
4
-
5
-
From the [VSCode web site](https://code.visualstudio.com/):
6
-
7
-
> Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is available for Windows, macOS and Linux. It comes with built-in support for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and Unity).
8
-
9
-
Here are some tips for getting up to speed with VSCode as you progress through this course.
3
+
Now that you're using VSCode here are some tips to use it effectively.
The `conditionOfCar` variable will be assigned the string `'new'` if the `age < 1` condition holds true, otherwise it is assigned the string `'used'`.
103
103
104
+
It is always possible to rewrite a ternary operator as an `if-then-else` statement, for example:
105
+
106
+
```js
107
+
let conditionOfCar;
108
+
if (age <1) {
109
+
conditionOfCar ='new';
110
+
} else {
111
+
conditionOfCar ='used';
112
+
}
113
+
```
114
+
115
+
Note that you can't use `const` here for `conditionOfCar` because we can't combine declaration and initialization in a single statement. Therefore we must now use `let`.
116
+
104
117
It is **not** recommended to use the conditional operator if you do not intend to use its value:
Copy file name to clipboardExpand all lines: fundamentals/functions.md
+27-1Lines changed: 27 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,32 @@
1
1
# Functions
2
2
3
-
A function is a reusable piece of code (see _Why Use Functions_ below). Functions are *very* important in JavaScript, to the extent that some people call JavaScript a "function-oriented" language. As mentioned above, variables can be of type function. In fact, *every function is a variable*.
3
+
Consider this **function** from [high-school math](https://www.mathplanet.com/education/algebra-2/how-to-graph-functions-and-linear-equations/functions-and-linear-equations):
4
+
5
+
> 𝑓(x) = x + 7
6
+
>
7
+
> _if x = 2 then_
8
+
>
9
+
> 𝑓(2) = 2 + 7 = 9
10
+
11
+
The value of the function 𝑓(x) is dependent on the value you supply for its argument x. (Instead of the term 'argument', sometimes the word 'parameter' is used).
12
+
13
+
Here is the equivalent JavaScript function:
14
+
15
+
```js
16
+
// function definition
17
+
functionf(x) {
18
+
return x +7;
19
+
}
20
+
21
+
// call the function and log its value for x = 2
22
+
console.log(f(2)); // -> 9
23
+
```
24
+
25
+
This function adds 7 to the value of its argument. Whenever we need to add 7 to some number we can reuse this same function over and over again.
26
+
27
+
During execution, the value of x in the function body (the part between the curly braces) is substituted with the value 'passed' during the function call.
28
+
29
+
A function thus is a reusable piece of code (see _Why Use Functions_ below). Functions are *very* important in JavaScript, to the extent that some people call JavaScript a "function-oriented" language. As mentioned above, variables can be of type function. In fact, *every function is a variable*.
4
30
5
31
The following two pieces of code have the exact same result:
For illustrative purposes we can add a `console.log` statement to our mapping function and see what we get passed as second and third argument:
43
+
For illustrative purposes we can add a `console.log`<sup>†</sup> statement to our mapping function and see what we get passed as second and third argument:
44
44
45
45
```js
46
46
constnumbers= [3, 5, 2, 7];
@@ -66,6 +66,8 @@ For each of the first four lines in the output (from the `console.log` inside th
66
66
67
67
As is usual in JavaScript you do not necessarily have to use all the parameters that were passed to the `mapFn` function. In fact, in many cases you will only need the first argument (the current array element) as we saw in the first example.
68
68
69
+
<sup>†</sup>You should normally not use `console.log` inside the function you pass to the `map` (or `filter`) method. These functions should also **not modify** any variables outside their own function scope, although they can reference these variables for read-only purposes. In computer science terms, these functions should be [pure with no 'side-effects'](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976).
70
+
69
71
## Array#filter()
70
72
71
73
The **filter()** method returns a new array with all elements that pass the test implemented by a user-supplied (predicate\*) function.
Copy file name to clipboardExpand all lines: fundamentals/naming_conventions.md
+6-1Lines changed: 6 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -2,7 +2,7 @@
2
2
3
3
## Background
4
4
5
-
In programming you will need to come up with appropriate names for your variablesand functions.
5
+
In programming you will need to come up with appropriate names for your variables, functions and function parameters.
6
6
7
7
> _The most important consideration in naming a variable is that the name fully and accurately describes the entity the variable represents. An effective technique for coming up with a good name is to state in words what the variable represents. Often that statement itself is the best variable name. It’s easy to read because it doesn’t contain cryptic abbreviations, and it’s unambiguous. Because it’s a full description of the
8
8
entity, it won’t be confused with something else. And it’s easy to remember because the name is similar to the concept._
@@ -86,6 +86,11 @@ class Movie {
86
86
}
87
87
```
88
88
89
+
## Reserved keywords
90
+
91
+
Certain names are reserved by JavaScript for its own use. You cannot use the names for your variable. For example, you can't name a variable `if`.
92
+
93
+
For a complete list of reserved names, see the MDN page for [Keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords).
Copy file name to clipboardExpand all lines: fundamentals/scope.md
+79-30Lines changed: 79 additions & 30 deletions
Original file line number
Diff line number
Diff line change
@@ -9,46 +9,50 @@ Definition from [Dictionary.com](http://www.dictionary.com/browse/scope):
9
9
10
10
If you imagine yourself as the computer that is executing your JavaScript code, you can think of scope as meaning:
11
11
12
-
> what you can see from where your are
12
+
> what you can see from where you are
13
13
14
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
15
16
16
## Global scope
17
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.
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 in general you must avoid creating variables and functions in global scope unless you have specific reasons to do so.
19
+
20
+
Consider the example below:
19
21
20
22
```js
21
-
a =10; // don't do this
23
+
a ='Hello'; // don't do this
22
24
console.log(a);
23
25
```
24
26
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 a mistake and with ES5 introduced `strict` mode: place the string `'use strict';` at the top of your file.
27
+
In this example we have assigned the value `'Hello'` 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 a mistake and with ES5 introduced `strict` mode: place the string `'use strict';` at the top of your file. This now causes our code to fail with a run-time error when forgetting to 'declare' our variables.
26
28
27
29
```js
28
30
'use strict';
29
-
a =10; // produces: ReferenceError: a is not defined
31
+
a ='Hello'; // produces: ReferenceError: a is not defined
30
32
console.log(a);
31
33
```
32
34
33
35
You can correct this by declaring your variable with `let`, `const` or `var`:
34
36
35
37
```js
36
38
'use strict';
37
-
let a =10;
39
+
var a ='Hello';
38
40
console.log(a);
39
41
```
40
42
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.
43
+
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).
44
+
45
+
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
46
43
47
## Local scope
44
48
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.
49
+
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 in that function body only: from the outside, you can't look in.
46
50
47
51
```js
48
52
'use strict';
49
53
50
54
functionmyFunction() {
51
-
consta=10;
55
+
consta='Hello';
52
56
console.log(a);
53
57
}
54
58
@@ -57,63 +61,108 @@ myFunction();
57
61
// console.log(a); <= this would produce: ReferenceError: a is not defined
58
62
```
59
63
60
-
But from the inside you can look out. In the example below the variable `b` is visible from inside the function body.
64
+
But from the inside you can look out. In the example below the variable `a` is visible from inside the function body.
61
65
62
66
```js
63
67
'use strict';
64
68
65
-
constb='Hello';
69
+
consta='Hello';
66
70
67
71
functionmyFunction() {
68
-
consta=10;
69
-
console.log(a);
70
-
console.log(b);
72
+
constb=', world';
73
+
console.log(a + b);
71
74
}
72
75
73
76
myFunction();
74
77
```
75
78
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.
79
+
You might think that the variable `a` 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 get `myFunction` out of the global scope by using, what is called, an **IIFE** to create a **local scope** (or, with ES6, by placing the function definition in a block to create a **block scope**). See further down below.
77
80
78
81
## Block scope
79
82
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.
83
+
The keywords `let` and `const` were introduced in ES6 as alternatives to the existing`var` keyword. 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
84
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 variable `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.
85
+
A new block scope (sometimes called _lexical_ scope) is created whenever you create a block of code inside a pair of curly braces. (Exception: the curly braces used to enclose the body of a function definition do not create a block scope. Instead, a **local scope**is created as discussed in the previous section.)
83
86
84
-
## Guidance
87
+
Variables defined with `let` and `const` at the file level (i.e., not inside a function or a block) are considered to be in a file-level block scope ('script' scope). That's why the variable `a` in the previous code snippet is not in global scope. Had we replaced `const a` with `var a` then variable `a`_would be_ in global scope.
88
+
89
+
## Scope Example
90
+
91
+
In the figure below we show an example bringing all scope types together. The code fragment on the right-hand side is executed by means of a `<script>` tag in `index.html`. The scope hierarchy shows the state of the scopes at the execution point indicated by the red triangle.
92
+
93
+

94
+
95
+
Let's go through these scopes from the top down:
96
+
97
+
- The `alert` function and the `document` object are placed in **global scope** by the browser at start-up (along with many other predefined 'system' variables). The `myFunction` function originates from our code snippet.
98
+
- The next scope shown is a **block scope** at the file level (our file `app.js` loaded up with a `<script>` tag). Variables defined outside of a block or function in this file will be visible from any location within the file. This holds true for the variable `a`.
99
+
- Next comes the **local scope** of the function `myFunction`. It contains the variables `b`, `h1` and `root`.
100
+
- The most inner scope is the **block scope** exists within the `if` statement block only. This is the scope that holds the variable `c`.
101
+
102
+
### Variable resolution
103
+
104
+
Let's consider the statement below taken from the example code snippet and examine how the variable references `a`, `b` and `c` are resolved by 'walking the scope chain'.
105
+
106
+
```js
107
+
h1.innerHTML= a + b + c;
108
+
```
85
109
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.
110
+
Variable resolution proceeds by attempting to resolve a variable reference from the current scope (i.e., at the point of reference), through intermediate scopes and ultimately ending in global scope, in the direction of the arrows.
87
111
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:
112
+
| Variable | Resolution |
113
+
| -------- | ---------- |
114
+
|`c`| This variable is defined in the current (block) scope and is resolved immediately. |
115
+
|`b`| After failing to resolve this variable from the current (block) scope, JavaScript walks up the scope chain and finds its definition in the local (function) scope. |
116
+
|`a`| To resolve this variable the JavaScript engine must hop up to the block scope at the file level. |
117
+
118
+
For the statement below, taken again from the code snippet in the picture, the JavaScript engine must walk the scope chain starting from the local (function) scope up to the global scope to find the definition of `document`.
89
119
90
120
```js
91
-
consth1=document.createElement('h1');
121
+
constroot=document.getElementById('root')
92
122
```
93
123
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.
124
+
## Guidance
125
+
126
+
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 have access to 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 nearest scope that is common to the points of need.
95
127
96
-
## IFFE
128
+
## IIFE
97
129
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.
130
+
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 IIFEs.
99
131
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.
132
+
To use an IIFE 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
133
102
134
```js
103
135
(function () {
104
136
'use strict';
105
137
106
-
constb='Hello';
138
+
consta='Hello';
107
139
108
140
functionmyFunction() {
109
-
consta=10;
110
-
console.log(a);
111
-
console.log(b);
141
+
constb=', world!';
142
+
console.log(a + b);
112
143
}
113
144
114
145
myFunction();
115
146
})();
116
147
```
117
148
118
-
More info on MDN: [IFFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
149
+
More info on MDN: [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)
150
+
151
+
## IIFE alternative (ES6)
152
+
153
+
In ES6 you can replace the IIFE by a simple block, like this, to achieve the same effect.
0 commit comments