Skip to content

Commit 9f2afe4

Browse files
committed
Further notes and homework for JS review
1 parent e095ade commit 9f2afe4

3 files changed

Lines changed: 326 additions & 0 deletions

File tree

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
### Javascript review week 3 - Part 2
2+
Jason indicated that you'll need to know the following before starting the Node class (remember Node is just Javascript in a different environment - and you KNOW JS already - right?!?!)
3+
4+
```
5+
From Jason:
6+
jason [9:11 AM]
7+
@timirkaria the most important topics will be sync/async and ajax. That and basic syntax (named and anonymous functions, callbacks, scope) should be sufficient!
8+
```
9+
10+
### AJAX
11+
Stands for *A*syncrhonous *J*avascript *A*nd *X*ml (think of XML as the old JSON) but now it's AJA*J* but that doesn't sound as good.
12+
13+
So here's an example of a SYNCHRONOUS request (it waits for the request to come back before continuing)
14+
15+
Code from: `https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Example_HTTP_synchronous_request`
16+
17+
```
18+
var SECRET_MESSAGE_URL = 'https://gist.githubusercontent.com/tkaria/08325583e7411f7de6b80871780fd917/raw/61dae2869ae5013652bbeba1da2487097d8869b1/SecretMessage.txt'
19+
var request = new XMLHttpRequest(SECRET_MESSAGE_URL);
20+
request.open('GET', SECRET_MESSAGE_URL, false); // `false` makes the request synchronous
21+
request.send(null);
22+
23+
if (request.status === 200) {
24+
console.log(request.responseText);
25+
console.log('Received the response');
26+
}
27+
console.log('Made the request')
28+
29+
```
30+
31+
And here's an example of an ASYNCHRONOUS version of the same request as above. Look carefully at the output.
32+
33+
```
34+
var SECRET_MESSAGE_URL = 'https://gist.githubusercontent.com/tkaria/08325583e7411f7de6b80871780fd917/raw/61dae2869ae5013652bbeba1da2487097d8869b1/SecretMessage.txt'
35+
var xhr = new XMLHttpRequest();
36+
xhr.open("GET", SECRET_MESSAGE_URL, true);
37+
xhr.onload = function (e) {
38+
if (xhr.readyState === 4) {
39+
if (xhr.status === 200) {
40+
console.log(xhr.responseText);
41+
console.log('Received the response');
42+
} else {
43+
console.error(xhr.statusText);
44+
}
45+
}
46+
};
47+
xhr.onerror = function (e) {
48+
console.error(xhr.statusText);
49+
};
50+
xhr.send(null);
51+
console.log('Made the request');
52+
```
53+
54+
### What's happening here?
55+
As always - read the docs first...
56+
`https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest`
57+
58+
Create a new request and open it (lines 2 and 3)
59+
Tell the request object what function to call when when the contents of the request are loaded. Inside the ANONYMOUS function which takes a parameter `e` we check the response code from the request (this is just HTTP stuff - nothing special). If the reponse code is good (200) then we print what we got.
60+
61+
More interesting is the order of the print statements. In the first example we saw the message `Received the response` **BEFORE** we saw the `Made the request` message because the program waited to get the response and print it before continuing to run.
62+
63+
In this case we see the `Made the request` message before we see the response because the program keeps running while waiting for the response. When the response is finally received it is printed before writing the `Received the response` to the console.
64+
65+
Note that we used an anonymous function here - it has no name. There's nothing special about an anonymous function. We could equally use a named function in the above example:
66+
67+
```
68+
var SECRET_MESSAGE_URL = 'https://gist.githubusercontent.com/tkaria/08325583e7411f7de6b80871780fd917/raw/61dae2869ae5013652bbeba1da2487097d8869b1/SecretMessage.txt'
69+
70+
var xhr = new XMLHttpRequest();
71+
function NOT_ANONYMOUS_ON_LOAD_FUNCTION(parameter) {
72+
if (xhr.readyState === 4) {
73+
if (xhr.status === 200) {
74+
console.log(xhr.responseText);
75+
console.log('Received the response');
76+
} else {
77+
console.error(xhr.statusText);
78+
}
79+
}
80+
}
81+
xhr.open("GET", SECRET_MESSAGE_URL, true);
82+
xhr.onload = NOT_ANONYMOUS_ON_LOAD_FUNCTION; // Note: we are not CALLING the function - there are no ()
83+
// We'll leave the error function the way it is and you can change it to a named function
84+
xhr.onerror = function (e) {
85+
console.error(xhr.statusText);
86+
};
87+
xhr.send(null);
88+
console.log('Made the request');
89+
90+
```
91+
92+
### The big idea:
93+
94+
#### Sync / Async
95+
Make requests without waiting for the response and just get "notified" when the response happens. That's the asyncrhonous part - don't wait for it and stop everything else just let me know when it happens. How can the computer let you know? You tell it what to do when the async function is ready (has something to say - success or failure)
96+
97+
#### Named and anonymous functions
98+
Some functions have names and some don't. Sometimes you just want to use a function to pass it to another function so you don't need to name it. It never needs to be called outside of the function that you're passing it to so it doesn't need a name.
99+
The simplest asynchonous function that you will see all over the place is called `setTimeout` (right now you should be reaching for a new tab and typing `MDN setTimeout` into Google). Be patient when running the below - it takes 3 seconds...
100+
101+
For example (using a named function):
102+
```
103+
function timeoutFunction() {
104+
console.log('Starting timeoutFunction');
105+
console.log('Ending timeoutFunction');
106+
}
107+
setTimeout(timeoutFunction, 3000);
108+
console.log('After timeoutFunction');
109+
```
110+
111+
For example (using an anonymous function):
112+
```
113+
setTimeout(function() {
114+
console.log('Starting timeoutFunction');
115+
console.log('Ending timeoutFunction');
116+
} , 3000);
117+
console.log('After timeoutFunction');
118+
```
119+
120+
For example (using an anonymous fat arrow function):
121+
```
122+
setTimeout(() => { console.log('Starting timeoutFunction');
123+
console.log('Ending timeoutFunction');
124+
} , 3000);
125+
console.log('After timeoutFunction');
126+
```
127+
128+
#### Callbacks
129+
What to do when the result of an async request is returned. Remember that requests can succeed as well as fail. Plan for (AND TEST) both.
130+
131+
#### Scope
132+
I think we covered this pretty well with our discussion of closures in the last class but let me know if you need more.
133+
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
### Javascript review week 3
2+
Read this - you may not understand it all but please read it before you read anything else about closures. The reason is that this is source material - this is the primary documentation. It is written very technically and in a bit of a boring way but there's a reason (as we talked about in class). The reason is to be clear so the language is precise and technical. It's OK if you don't get it now but just read it and it will stay in the back of your head.
3+
https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
4+
5+
Please TYPE thse exercises - do NOT copy and paste. BEFORE you run them please make a guess in your head about what will happen.
6+
```
7+
function init() {
8+
var name = 'Mozilla'; // name is a local variable created by init
9+
function displayName() { // displayName() is the inner function, a closure
10+
alert(name); // use variable declared in the parent function
11+
}
12+
displayName();
13+
}
14+
init();
15+
```
16+
17+
```
18+
function init() {
19+
var name = 'Mozilla'; // name is a local variable created by init
20+
function displayName() { // displayName() is the inner function, a closure
21+
alert(name); // use variable declared in the parent function
22+
}
23+
}
24+
displayName();
25+
```
26+
27+
```
28+
var name = 'Hack your future'
29+
function init() {
30+
var name = 'Mozilla'; // name is a local variable created by init
31+
function displayName() { // displayName() is the inner function, a closure
32+
alert(name); // use variable declared in the parent function
33+
}
34+
displayName();
35+
}
36+
init();
37+
```
38+
39+
```
40+
var name = 'Hack your future'
41+
function init(name) {
42+
function displayName(name) { // displayName() is the inner function, a closure
43+
alert(name); // use variable declared in the parent function
44+
}
45+
displayName(name);
46+
}
47+
init('Hack your future again')
48+
```
49+
50+
Now read this: http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop
51+
52+
And try out the examples - please make SURE you understand what is happening. Ask questions if you do not.
53+
54+
Same instructions as above but now for Arrow functions (remember this is not intended to confuse you - it's just code).
55+
### Arrow functions
56+
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
57+
Then read this.
58+
http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6/28135120#28135120
59+
60+
This is a normal function:
61+
```
62+
function sayHello(name) {
63+
return 'Hello ' + name;
64+
}
65+
```
66+
67+
Same as above with arrow (fat arrow) notation - shorthand notation. This is easy to mess up. Notice no return.
68+
```
69+
var sayHello2 = (name) => 'Hello ' + name;
70+
```
71+
72+
Same as above with arrow (fat arrow) notation - shorthand notation. Better - easier to read - with return.
73+
```
74+
var sayHello2 = (name) => {return 'Hello ' + name;}
75+
```
76+
77+
Think about this one
78+
```
79+
function Person(firstName) {
80+
this.firstName = firstName;
81+
}
82+
```
83+
84+
Looks the same but what happens? See if you can figure out why from reading the documentation.
85+
```
86+
var Person = (firstName) => {this.firstName = firstName}
87+
```
88+
89+
Closures and async functions
90+
What's going on here - I would expect 3 alerts with 1,2,3 in them but noooooooooo
91+
```
92+
var i;
93+
for (i = 0; i < 3; i++) {
94+
setTimeout(function callBackFunction() {
95+
alert(i);
96+
}, 100);
97+
}
98+
```
99+
100+
### Make the above function do what we think it should do.
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
### Javascript review week 3
2+
Read this - you may not understand it all but please read it before you read anything else about closures. The reason is that this is source material - this is the primary documentation. It is written very technically and in a bit of a boring way but there's a reason (as we talked about in class). The reason is to be clear so the language is precise and technical. It's OK if you don't get it now but just read it and it will stay in the back of your head.
3+
https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
4+
5+
Please TYPE thse exercises - do NOT copy and paste. BEFORE you run them please make a guess in your head about what will happen.
6+
```
7+
function init() {
8+
var name = 'Mozilla'; // name is a local variable created by init
9+
function displayName() { // displayName() is the inner function, a closure
10+
alert(name); // use variable declared in the parent function
11+
}
12+
displayName();
13+
}
14+
init();
15+
```
16+
17+
```
18+
function init() {
19+
var name = 'Mozilla'; // name is a local variable created by init
20+
function displayName() { // displayName() is the inner function, a closure
21+
alert(name); // use variable declared in the parent function
22+
}
23+
}
24+
displayName();
25+
```
26+
27+
```
28+
var name = 'Hack your future'
29+
function init() {
30+
var name = 'Mozilla'; // name is a local variable created by init
31+
function displayName() { // displayName() is the inner function, a closure
32+
alert(name); // use variable declared in the parent function
33+
}
34+
displayName();
35+
}
36+
init();
37+
```
38+
39+
```
40+
var name = 'Hack your future'
41+
function init(name) {
42+
function displayName(name) { // displayName() is the inner function, a closure
43+
alert(name); // use variable declared in the parent function
44+
}
45+
displayName(name);
46+
}
47+
init('Hack your future again')
48+
```
49+
50+
Now read this: http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop
51+
52+
And try out the examples - please make SURE you understand what is happening. Ask questions if you do not.
53+
54+
Same instructions as above.
55+
### Arrow functions
56+
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
57+
Then read this.
58+
http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6/28135120#28135120
59+
60+
This is a normal function:
61+
```
62+
function sayHello(name) {
63+
return 'Hello ' + name;
64+
}
65+
```
66+
Same as above with arrow (fat arrow) notation
67+
var sayHello2 = (name) => 'Hello ' + name;
68+
69+
70+
### Return examples
71+
```
72+
Return values
73+
function f1(x) {
74+
this.x = x + 1;
75+
return;
76+
}
77+
78+
function f2(x) {
79+
return this.x = x + 1;
80+
}
81+
```
82+
### Static members
83+
http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx
84+
85+
### Closures examples
86+
https://jsfiddle.net/78dg25ax/?utm_source=website&utm_medium=embed&utm_campaign=78dg25ax
87+
88+
### Why closures are helpful with async code:
89+
http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript
90+
91+
### Promises
92+
http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript
93+
https://www.youtube.com/watch?v=WBupia9oidU

0 commit comments

Comments
 (0)