Skip to content

Instantly share code, notes, and snippets.

@designviacode
Forked from amysimmons/js-tricky-bits.md
Created July 30, 2018 13:59
Show Gist options
  • Select an option

  • Save designviacode/6e4ae3893c4bacedb88a72c623535709 to your computer and use it in GitHub Desktop.

Select an option

Save designviacode/6e4ae3893c4bacedb88a72c623535709 to your computer and use it in GitHub Desktop.

Revisions

  1. @amysimmons amysimmons revised this gist Mar 13, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -38,7 +38,7 @@ say2(); // logs "Hello Bob"
    **Source: [Understanding JavaScript Closures With Ease][jsissexy]**

    - A closure is an inner function that has access to the outer (enclosing) function's variables
    - The closure has three scopes: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables
    - The closure has three scopes, all part of the same chain: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables
    - The inner function has access not only to the outer function’s variables, but also to the outer function's parameters

    ```
  2. @amysimmons amysimmons revised this gist Mar 13, 2016. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -19,6 +19,7 @@ Amy
    **Source: [How do JavaScript Closures Work][closuresstackoverflow]**

    - In JavaScript, if you use the function keyword inside another function, you are creating a closure
    - A regular function created in the global scope can also close over variables
    - The below code has a closure because the anonymous function *function() { console.log(text); }* is declared inside another function, *sayHello2()*

    ```
    @@ -37,7 +38,7 @@ say2(); // logs "Hello Bob"
    **Source: [Understanding JavaScript Closures With Ease][jsissexy]**

    - A closure is an inner function that has access to the outer (enclosing) function's variables
    - The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables
    - The closure has three scopes: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables
    - The inner function has access not only to the outer function’s variables, but also to the outer function's parameters

    ```
  3. @amysimmons amysimmons revised this gist Mar 13, 2016. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -326,7 +326,6 @@ function loop(){
    loop()
    ```

    3)

    ##Additional sources

  4. @amysimmons amysimmons revised this gist Mar 13, 2016. 1 changed file with 14 additions and 0 deletions.
    14 changes: 14 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,19 @@
    #Understanding closures, callbacks and promises

    For a code newbie like myself, callbacks, closures and promises are scary JavaScript concepts.

    10 months into my full-time dev career, and I would struggle to explain these words to a peer.

    So I decided it was time to face my fears, and try to get my head around each concept.

    Here are the notes from my initial reading. I'll continue to refine them as my understanding improves.

    I hope they help!

    Cheers,

    Amy

    ##Closures

    **Source: [How do JavaScript Closures Work][closuresstackoverflow]**
  5. @amysimmons amysimmons revised this gist Mar 13, 2016. 1 changed file with 17 additions and 16 deletions.
    33 changes: 17 additions & 16 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -4,8 +4,8 @@

    **Source: [How do JavaScript Closures Work][closuresstackoverflow]**

    - The below code has a closure because the anonymous function function() { console.log(text); } is declared inside another function, sayHello2()
    - In JavaScript, if you use the function keyword inside another function, you are creating a closure
    - The below code has a closure because the anonymous function *function() { console.log(text); }* is declared inside another function, *sayHello2()*

    ```
    function sayHello2(name) {
    @@ -17,8 +17,8 @@ var say2 = sayHello2('Bob');
    say2(); // logs "Hello Bob"
    ```

    - If you declare a function within another function, then the local variables can remain accessible after returning from the function you called.
    - This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). The code that we call references the variable 'text', which was a local variable of the function sayHello2().
    - If you declare a function within another function, then the local variables can remain accessible after returning from the function you called
    - This is demonstrated above, because we call the function say2() after we have returned from sayHello2(). The code that we call is still able to reference the variable 'text', which was a local variable of the function sayHello2()

    **Source: [Understanding JavaScript Closures With Ease][jsissexy]**

    @@ -28,13 +28,14 @@ say2(); // logs "Hello Bob"

    ```
    function showName (firstName, lastName) {
    var nameIntro = "Your name is ";
    // this inner function has access to the outer function's variables, including the parameter​
    function makeFullName () {
    return nameIntro + firstName + " " + lastName;
    }
    return makeFullName ();
    var nameIntro = "Your name is ";
    // this inner function has access to the outer function's variables, including the parameter​
    function makeFullName () {
    return nameIntro + firstName + " " + lastName;
    }
    return makeFullName ();
    }
    showName ("Amy", "Simmons"); // Your name is Amy Simmons
    @@ -67,7 +68,7 @@ surprise();
    **Source: [JavaScript The Good Parts][oreilly]**

    - Take the following example: a user interaction triggers a request to a server, and the response from the server should be displayed in the browser
    - A synchronous way of doing this would be:
    - A *synchronous* way of doing this would be:

    ```
    //synchronous example:
    @@ -77,7 +78,7 @@ response = send_request_synchronously(request);
    display(response)
    ```

    - Because the above code is *synchronous*, the program will wait for it to finish before moving on to another task
    - Because the above code is synchronous, the program will wait for it to finish before moving on to another task
    - If either the network or the server is slow, the user will be left waiting
    - A better way of doing this would be with an *asynchronous* request, which provides a 'callback' function which will be invoked once the server's response is received:

    @@ -150,7 +151,7 @@ increment(10, done);
    **Source: [Udacity JavaScript Promises][udacitypromises]**

    - Normally code is *synchronous* - one statement executes and there is a guarantee that the next statement will execute immediately afterwards
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order.
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order
    - Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code.

    **Source: [Promisejs.org][promisejs]**
    @@ -235,6 +236,7 @@ get('story.json').then(function(response) {
    **Source: [Eloquent JavaScript][eloquentjs]**

    - Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails
    - Simialr to the above example:

    ```
    funciton get(url){
    @@ -273,7 +275,7 @@ get("example/data.txt").then(function(text){
    - .then example: https://jsfiddle.net/z4978svf/1/
    - .catch example: https://jsfiddle.net/2wvj8j8u/

    ##Tasks to help my understanding:
    ##Tasks to help my understanding of closures, callbacks and promises:

    1) Log the numbers 1 to 10 in the console with one second intervals using a loop: https://jsfiddle.net/4kdua72m/2/

    @@ -310,8 +312,7 @@ function loop(){
    loop()
    ```

    3) Use promises for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon

    3)

    ##Additional sources

  6. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -268,6 +268,10 @@ get("example/data.txt").then(function(text){
    ```
    - Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

    **My JS Fidles:**

    - .then example: https://jsfiddle.net/z4978svf/1/
    - .catch example: https://jsfiddle.net/2wvj8j8u/

    ##Tasks to help my understanding:

  7. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 81 additions and 8 deletions.
    89 changes: 81 additions & 8 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -153,6 +153,85 @@ increment(10, done);
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order.
    - Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code.

    **Source: [Promisejs.org][promisejs]**

    - Promises help you naturally handle errors, and write cleaner code by not having callback parameters
    - A promise represents the result of an asynchronous operation. A promise is in one of three different states: pending, fulfilled or rejected
    - Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again)
    - We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
    - promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it

    **Source: [JavaScript Promise API][dwbpromises]**

    *Basic usage:*

    ```
    var p = new Promise(function(resolve, reject) {
    // Do an async task async task and then...
    if(/* good condition */) {
    resolve('Success!');
    }
    else {
    reject('Failure!');
    }
    });
    p.then(function() {
    /* do something with the result */
    }).catch(function() {
    /* error :( */
    })
    ```

    *Realistic example:*

    - A realistic example of using promises would be converting a get request to a promise-based task:

    ```
    // From Jake Archibald's Promises and Back:
    // http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promisifying-xmlhttprequest
    function get(url) {
    // Return a new promise.
    return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.onload = function() {
    // This is called even on 404 etc
    // so check the status
    if (req.status == 200) {
    // Resolve the promise with the response text
    resolve(req.response);
    }
    else {
    // Otherwise reject with the status text
    // which will hopefully be a meaningful error
    reject(Error(req.statusText));
    }
    };
    // Handle network errors
    req.onerror = function() {
    reject(Error("Network Error"));
    };
    // Make the request
    req.send();
    });
    }
    // Use it!
    get('story.json').then(function(response) {
    console.log("Success!", response);
    }, function(error) {
    console.error("Failed!", error);
    });
    ```

    **Source: [Eloquent JavaScript][eloquentjs]**

    - Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails
    @@ -189,13 +268,6 @@ get("example/data.txt").then(function(text){
    ```
    - Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

    **Source: [Promisejs.org][promisejs]**

    - Promises help you naturally handle errors, and write cleaner code by not having callback parameters
    - A promise represents the result of an asynchronous operation. A promise is in one of three different states: pending, fulfilled or rejected
    - Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again)
    - We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
    - promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it

    ##Tasks to help my understanding:

    @@ -254,4 +326,5 @@ loop()
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898
    [dwbpromises]: https://davidwalsh.name/promises
  8. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 9 additions and 2 deletions.
    11 changes: 9 additions & 2 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -237,6 +237,14 @@ loop()
    3) Use promises for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


    ##Additional sources

    - https://davidwalsh.name/promises
    - http://www.html5rocks.com/en/tutorials/es6/promises/
    - https://www.toptal.com/javascript/javascript-promises
    - http://www.javascriptkit.com/javatutors/javascriptpromises.shtml
    - https://spring.io/understanding/javascript-promises

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    @@ -246,5 +254,4 @@ loop()
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898

    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898
  9. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -199,7 +199,7 @@ get("example/data.txt").then(function(text){

    ##Tasks to help my understanding:

    1) Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/
    1) Log the numbers 1 to 10 in the console with one second intervals using a loop: https://jsfiddle.net/4kdua72m/2/

    ```
    for (var i = 0; i <= 10; i++) {
    @@ -216,7 +216,7 @@ for (var i = 0; i <= 10; i++) {
    //IIFE is the quickest way of creating a closure
    ```

    2) Log the numbers 1 to 10 in the console with one second intervals without using a loop (uses callbacks, recursion and closure): https://jsfiddle.net/v9qybf6x/2/
    2) Log the numbers 1 to 10 in the console with one second intervals without using a loop: https://jsfiddle.net/v9qybf6x/2/

    ```
    var i = 0;
  10. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 12 additions and 13 deletions.
    25 changes: 12 additions & 13 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -197,19 +197,7 @@ get("example/data.txt").then(function(text){
    - We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
    - promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898


    ####Tasks:
    ##Tasks to help my understanding:

    1) Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/

    @@ -249,3 +237,14 @@ loop()
    3) Use promises for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898

  11. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -209,7 +209,7 @@ get("example/data.txt").then(function(text){
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898


    ###Tasks:
    ####Tasks:

    1) Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/

    @@ -246,6 +246,6 @@ function loop(){
    loop()
    ```

    3) Use promises to for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon
    3) Use promises for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


  12. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -211,7 +211,7 @@ get("example/data.txt").then(function(text){

    ###Tasks:

    1. Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/
    1) Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/

    ```
    for (var i = 0; i <= 10; i++) {
    @@ -228,7 +228,7 @@ for (var i = 0; i <= 10; i++) {
    //IIFE is the quickest way of creating a closure
    ```

    2. Log the numbers 1 to 10 in the console with one second intervals without using a loop (uses callbacks, recursion and closure): https://jsfiddle.net/v9qybf6x/2/
    2) Log the numbers 1 to 10 in the console with one second intervals without using a loop (uses callbacks, recursion and closure): https://jsfiddle.net/v9qybf6x/2/

    ```
    var i = 0;
    @@ -246,6 +246,6 @@ function loop(){
    loop()
    ```

    3. Use promises to for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon
    3) Use promises to for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


  13. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 34 additions and 1 deletion.
    35 changes: 34 additions & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -211,8 +211,41 @@ get("example/data.txt").then(function(text){

    ###Tasks:

    1. Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/1/
    1. Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/2/

    ```
    for (var i = 0; i <= 10; i++) {
    (function(index) {
    setTimeout(function(){
    console.log(index);
    }, 1000 * index);
    })(i);
    }
    //the above uses an IIFE, an immediately invoked function expression
    //the IIFE takes in its own private copy of i
    //it console logs the index at 1000ms, 2000ms, 3000ms, etc
    //IIFE is the quickest way of creating a closure
    ```

    2. Log the numbers 1 to 10 in the console with one second intervals without using a loop (uses callbacks, recursion and closure): https://jsfiddle.net/v9qybf6x/2/

    ```
    var i = 0;
    function loop(){
    setTimeout(function(){
    console.log(i);
    i++;
    if (i <= 10){
    loop();
    }
    }, 1000)
    }
    loop()
    ```

    3. Use promises to for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


  14. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -209,3 +209,10 @@ get("example/data.txt").then(function(text){
    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898


    ###Tasks:

    1. Log the numbers 1 to 10 in the console with one second intervals using a loop (uses closure): https://jsfiddle.net/4kdua72m/1/
    2. Log the numbers 1 to 10 in the console with one second intervals without using a loop (uses callbacks, recursion and closure): https://jsfiddle.net/v9qybf6x/2/
    3. Use promises to for Six Degrees of Kevin Bacon: https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon


  15. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -191,7 +191,7 @@ get("example/data.txt").then(function(text){

    **Source: [Promisejs.org][promisejs]**

    -Promises help you naturally handle errors, and write cleaner code by not having callback parameters
    - Promises help you naturally handle errors, and write cleaner code by not having callback parameters
    - A promise represents the result of an asynchronous operation. A promise is in one of three different states: pending, fulfilled or rejected
    - Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again)
    - We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
  16. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -191,6 +191,12 @@ get("example/data.txt").then(function(text){

    **Source: [Promisejs.org][promisejs]**

    -Promises help you naturally handle errors, and write cleaner code by not having callback parameters
    - A promise represents the result of an asynchronous operation. A promise is in one of three different states: pending, fulfilled or rejected
    - Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again)
    - We use new Promise to construct the promise, the constructor is called immediately with two arguments - one that fulfils the promise and the other that rejects the promise
    - promise.done allows us to wait for the promise to be fulfilled or rejected before doing something with it

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
  17. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 7 additions and 7 deletions.
    14 changes: 7 additions & 7 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -147,6 +147,12 @@ increment(10, done);

    ##Promises

    **Source: [Udacity JavaScript Promises][udacitypromises]**

    - Normally code is *synchronous* - one statement executes and there is a guarantee that the next statement will execute immediately afterwards
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order.
    - Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code.

    **Source: [Eloquent JavaScript][eloquentjs]**

    - Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails
    @@ -183,12 +189,6 @@ get("example/data.txt").then(function(text){
    ```
    - Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

    **Source: [Udacity JavaScript Promises][udacitypromises]**

    - Normally code is *synchronous* - one statement executes and there is a guarantee that the next statement will execute immediately afterwards
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order.
    - Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code.

    **Source: [Promisejs.org][promisejs]**

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    @@ -200,6 +200,6 @@ get("example/data.txt").then(function(text){
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/

    [udacitypromises]: https://www.udacity.com/course/javascript-promises--ud898


  18. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -183,6 +183,12 @@ get("example/data.txt").then(function(text){
    ```
    - Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

    **Source: [Udacity JavaScript Promises][udacitypromises]**

    - Normally code is *synchronous* - one statement executes and there is a guarantee that the next statement will execute immediately afterwards
    - With *asynchronous* operations, you should assume that you have no idea when the operation will complete. You can't even assume that just because you send out one request first, and another request second, that they will return in that order.
    - Callbacks are the standard way of handling asynchrnous code in JavaScript, but promises are the best way to handle asynchronous code. This is because callbacks make error handling difficult, and lead to ugly nested code.

    **Source: [Promisejs.org][promisejs]**

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
  19. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 40 additions and 0 deletions.
    40 changes: 40 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -147,13 +147,53 @@ increment(10, done);

    ##Promises

    **Source: [Eloquent JavaScript][eloquentjs]**

    - Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails

    ```
    funciton get(url){
    return new Promise(function(succeed, fail){
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.addEventListener("load", function(){
    if(req.status < 400){
    succeed(req.responseText);
    }else{
    fail(new Error("Request failed: " + req.statusText));
    }
    });
    req.addEventListener("error", function(){
    fail(new Error("Network error"));
    });
    req.send(null);
    });
    }
    ```

    - The get function above receives a url, and returns a promise
    - The promise has a .then method which can be called with two functions, one to handle success, and the other to handle failure

    ```
    get("example/data.txt").then(function(text){
    console.log("data.txt: " + text);
    }, function(error){
    console.log('Failed to fetch data.txt: " + error);
    });
    ```
    - Calling .then produces a new promise, whose result depends on the return value of the first function we passed to then

    **Source: [Promisejs.org][promisejs]**

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/
    [eloquentjs]: http://eloquentjavascript.net/
    [promisejs]: https://www.promisejs.org/



  20. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 18 additions and 1 deletion.
    19 changes: 18 additions & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -127,6 +127,23 @@ fileObject = open(file, writeToFile)

    **My own attempt: [Also on JS Fiddle][jsfiddlecallbacks]**

    ```
    //the callback function
    function done(){
    console.log("Done");
    }
    //the parent function
    function increment(num, callBack){
    for(var i = 0; i <= num; i++){
    console.log(i);
    }
    return callBack();
    }
    //the callback function is passed to the increment function
    increment(10, done);
    ```

    ##Promises

    @@ -136,7 +153,7 @@ fileObject = open(file, writeToFile)
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/1/
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/2/



  21. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -125,6 +125,9 @@ fileObject = open(file, writeToFile)
    //once the file is opened we write to it, but while we wait we can do other things
    ```

    **My own attempt: [Also on JS Fiddle][jsfiddlecallbacks]**


    ##Promises

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
  22. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -133,6 +133,7 @@ fileObject = open(file, writeToFile)
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o
    [jsfiddlecallbacks]: https://jsfiddle.net/e62tzzcr/1/



  23. @amysimmons amysimmons revised this gist Mar 12, 2016. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -70,19 +70,19 @@ surprise();
    - A synchronous way of doing this would be:

    ```
    //a synchronous example:
    //synchronous example:
    request = prepare_the_request();
    response = send_request_synchronously(request);
    display(response)
    ```

    - Because the above code is *synchronous*, meaning the program will wait for it to finish before moving on to another task
    - Because the above code is *synchronous*, the program will wait for it to finish before moving on to another task
    - If either the network or the server is slow, the user will be left waiting
    - A better way of doing this would be with an *asynchronous* request, which provides a 'callback' function which will be invoked once the server's response is received:

    ```
    //an asynchronous example:
    //asynchronous example:
    request = prepare_the_request();
    response = send_request_asynchronously(request, function (response) {
    @@ -102,7 +102,7 @@ A callback function is a function which is:

    **Source: [How to explain callbacks in plain english?][callbacksstackoverflow2]**

    - A callback is any function that is called by another function which takes the first function as a parameter
    - A callback is any function that is called by another function, which takes the first function as a parameter
    - Consider how programmers normally write to a file:

    ```
  24. @amysimmons amysimmons revised this gist Mar 11, 2016. No changes.
  25. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 23 additions and 0 deletions.
    23 changes: 23 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -102,6 +102,29 @@ A callback function is a function which is:

    **Source: [How to explain callbacks in plain english?][callbacksstackoverflow2]**

    - A callback is any function that is called by another function which takes the first function as a parameter
    - Consider how programmers normally write to a file:

    ```
    fileObject = open(file)
    //now that we have WAITED for the file to open, we can write to it
    fileObject.write("We are writing to the file.")
    //now we can continue doing the other, totally unrelated things our program does
    ```

    - In the above example, we wait for the file to open, before we write to it.
    - This blocks the flow of execution, and our program cannot do any of the other things it might need to do
    - This is where callbacks are useful:

    ```
    //we pass writeToFile (a callback function) to the open function
    fileObject = open(file, writeToFile)
    //execution continues flowing -- we don't wait for the file to be opened
    //once the file is opened we write to it, but while we wait we can do other things
    ```

    ##Promises

    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
  26. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -94,6 +94,12 @@ response = send_request_asynchronously(request, function (response) {

    **Source: [What is a callback function?][callbacksstackoverflow1]**

    A callback function is a function which is:

    - passed as an argument to another function
    - is invoked after some kind of event
    - once its parent function completes, the function passed as an argument is then called

    **Source: [How to explain callbacks in plain english?][callbacksstackoverflow2]**

    ##Promises
  27. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 10 additions and 2 deletions.
    12 changes: 10 additions & 2 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@

    ##Closures

    **Source: [How do JavaScript Closures Work][stackoverflow]**
    **Source: [How do JavaScript Closures Work][closuresstackoverflow]**

    - The below code has a closure because the anonymous function function() { console.log(text); } is declared inside another function, sayHello2()
    - In JavaScript, if you use the function keyword inside another function, you are creating a closure
    @@ -92,10 +92,18 @@ response = send_request_asynchronously(request, function (response) {

    - When you execute something asynchronously, the program can move on to another task before the request finishes

    **Source: [What is a callback function?][callbacksstackoverflow1]**

    **Source: [How to explain callbacks in plain english?][callbacksstackoverflow2]**

    ##Promises

    [stackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [closuresstackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do
    [callbacksstackoverflow1]: http://stackoverflow.com/questions/824234/what-is-a-callback-function
    [callbacksstackoverflow2]: http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o



  28. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -82,7 +82,7 @@ display(response)
    - A better way of doing this would be with an *asynchronous* request, which provides a 'callback' function which will be invoked once the server's response is received:

    ```
    //an synchronous example:
    //an asynchronous example:
    request = prepare_the_request();
    response = send_request_asynchronously(request, function (response) {
  29. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 4 additions and 3 deletions.
    7 changes: 4 additions & 3 deletions js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -77,10 +77,9 @@ response = send_request_synchronously(request);
    display(response)
    ```

    - Because the above code is synchronous, the program will wait for it to finish before moving on to another task
    - Because the above code is *synchronous*, meaning the program will wait for it to finish before moving on to another task
    - If either the network or the server is slow, the user will be left waiting
    - A better way of doing this would be with an asynchronous request, which provides a 'callback' function which will be invoked once the server's response is received
    - When you execute something asynchronously, you can move on to another task before it finishes
    - A better way of doing this would be with an *asynchronous* request, which provides a 'callback' function which will be invoked once the server's response is received:

    ```
    //an synchronous example:
    @@ -91,6 +90,8 @@ response = send_request_asynchronously(request, function (response) {
    });
    ```

    - When you execute something asynchronously, the program can move on to another task before the request finishes

    ##Promises

    [stackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
  30. @amysimmons amysimmons revised this gist Mar 11, 2016. 1 changed file with 25 additions and 1 deletion.
    26 changes: 25 additions & 1 deletion js-tricky-bits.md
    Original file line number Diff line number Diff line change
    @@ -64,13 +64,37 @@ surprise();

    ##Callbacks

    **Source: [JavaScript The Good Parts][oreilly]**

    ##Promises
    - Take the following example: a user interaction triggers a request to a server, and the response from the server should be displayed in the browser
    - A synchronous way of doing this would be:

    ```
    //a synchronous example:
    request = prepare_the_request();
    response = send_request_synchronously(request);
    display(response)
    ```

    - Because the above code is synchronous, the program will wait for it to finish before moving on to another task
    - If either the network or the server is slow, the user will be left waiting
    - A better way of doing this would be with an asynchronous request, which provides a 'callback' function which will be invoked once the server's response is received
    - When you execute something asynchronously, you can move on to another task before it finishes

    ```
    //an synchronous example:
    request = prepare_the_request();
    response = send_request_asynchronously(request, function (response) {
    display(response);
    });
    ```

    ##Promises

    [stackoverflow]: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work
    [jsissexy]: http://javascriptissexy.com/understand-javascript-closures-with-ease/
    [jsfiddleclosure]: https://jsfiddle.net/wgfsajLL/
    [oreilly]: http://shop.oreilly.com/product/9780596517748.do