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.
Understanding closures, callbacks and promises in JavaScript

#Understanding closures, callbacks and promises

##Closures

Source: How do JavaScript Closures Work

  • 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
function sayHello2(name) {
    var text = 'Hello ' + name; // Local variable
    var say = function() { console.log(text); }
    return say;
}
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().

Source: Understanding JavaScript Closures With Ease

  • 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 inner function has access not only to the outer function’s variables, but also to the outer function's parameters
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 ();
}

showName ("Amy", "Simmons"); // Your name is Amy Simmons

My own attempt: Also on JS Fiddle

//this example uses a closure because:
//a function is defined inside another function
//the inner function has access to the outer functions variables, 'text'
//the outer function's variables can be accessed even after the outer function is called

function surpriseMe(surprise){
	var text = "Today you will be surprised with " + surprise;
  
  function revealSurprise(){
  	alert(text);
  }
  
  return revealSurprise;
}

var surprise = surpriseMe("1000 puppy dogs");
surprise();

##Callbacks

Source: JavaScript The Good Parts

  • 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:
//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:
//asynchronous example:

request = prepare_the_request();
response = send_request_asynchronously(request, function (response) {
	display(response);
});
  • When you execute something asynchronously, the program can move on to another task before the request finishes

Source: What is a callback function?

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?

  • 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

My own attempt: Also on JS Fiddle

//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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment