Returning in Javascript and Intoduction to Closures

Functions return a value of undefinded by default, unless we explicitly tell it to return another value.

How do we do that?

function returnSomething() {
	return 5;
}

When we run the function it will return the value of 5. We will see this in the developer console, but if we want to do something with it in our code we need to return it to a variable so we can access it once the function has completed running. So usually we do something like this:

var myVar = returnSomething();

The function executes and the value of 5 is returned to the myVar variable. So if we try to access it:

console.log(myVar);

We will get the value of 5. In this case we returned a number, a primitive value, but we can return other things too…

function returnSomething2() {
	// this object is not attached to a variable name yet. In a sense its an anonymous object, although that's not a terminology that's often used.
	return {name: "Tedwood"};
}
var myObj = returnSomething2();

The var myObj now contains or refers to the object that was returned from the call to returnSomething2. So now we can access properties of that object through its identifier myObj, which is essentially like giving that object a name or more precisely, an identifier. So myObj.name yields “Tedwood”.

How about returning a function?

function returnSomething3() {
    // inner function to return
	return function() { 
		alert("Hello"); 
	};
}
var myFn = returnSomething3(); 

Note that the inner function is anonymous, so when its returned into the variable myFn, we now have a way of identifying it and hence accessing it. So myFn is sort of like a ‘name’ for that function.

So we can now call myFn() with parens after it to make it execute the function. We should see an alert box with “Hello”.

Note also that if we just run returnSomething3 without assigning it to a variable, like the following: returnSomething3(); we won’t see the alert box because the outer function is not executing the inner function, it is only returning a function definition that can be ran later.

Closures

Now that we know how to return a function from another function, we can look at the topic of closures, which is much easier to grasp than it might at first seem.

Essentially, our returned function can still access the variables and parameters of the outer function, even after the outer function has finished executing.

function returnSomething4() {
	var x = 8;
    // inner function to return. It will 'close' over the variables inside the outer function, so that when we later run it, it will still be able to access those variables. 
	return function() { 
		alert(x); 
	};
}
var myFn = returnSomething4(); // alerts 8

Note: the inner function which is returned is referred to as a closure because it closes over the variables that exist in the execution context of the outer function.