Unit 3: More on Working with Functions
In this unit, you will expand your knowledge of JavaScript functions which we covered in the first course. You will learn how to use the this
keyword correctly and create and use nested, recursive, and higher-order functions. By the end of the unit, you will write a recursive function.
Completing this unit should take you approximately 2 hours.
Upon successful completion of this unit, you will be able to:
- compare types of functions;
- explain the difference between scope and closure;
- model the
this
keyword in bind, call, and apply functions; - compare nested, recursive, and high-order functions; and
- develop code that uses recursive functions.
3.1: Comparing Types of Functions
In the previous course, we learned different types of functions. Functions eliminate the need to write the same code repeatedly, which saves time. Functions also make your code much more manageable by segmenting a huge program into several functions, which makes modification efficient. The material in this section reviews functions and then covers using a constructor with a function.
A function is a block of code that can be reused multiple times as needed. Functions may have zero or more parameters and can return values or not. In JavaScript, functions can be created using various methods, such as a function declaration or function expression.
Function Declaration:
function panda() { //do something in here
//return something (or not)
}
Function Expression:
var panda = function(){
//do something
}In JavaScript, a function returns a value by returning the value in the "return" statement to where the function was called. For example:
sum = add(a,b)
When we call theadd(a,b)
function and it executes its return statement, that returned value will be stored in the sum variable.
Anonymous refers to not having a name or any means of identification. When using an anonymous function in JavaScript, your function will not be named. For example,
let x = function() { console.log("I am anonymous"); }
; In this case, "x" is the variable assigned to the anonymous function and NOT its actual name.Functions can be created using a "function" statement or the
Function()
constructor. Dynamic functions are created when defining functions with the "new" operator and Function() constructor. Constructors not only create new objects but also specify the behaviors and properties of those objects.
3.2: Scope and Closure
When working with variables in Javascript, you need to understand the scope and where to access a variable. This section aims to simplify how the scope of variables is used in a general program and inside functions, where the scope can be more complicated.
Scope refers to the variables available to a code segment at a given time. If a variable is out of scope, JavaScript cannot access it. The two types of scope are local and global. Global variables are declared outside of a block and can be accessed globally. Local variables are declared inside a block, and only that block can access them.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). Simplified, a function inside another function can access the variables from the outer (parent) function. This is a type of encapsulation in JavaScript.
Scope in JavaScript can be broken into two types: local and global. When you declare a variable inside a function, a function will have its local scope. A global variable will be declared outside of functions and can be used throughout the code segments. When using global variables, you must be careful because there are rules for when your global and local variables have the same name and how the precedence will work. Watch this video for how scope is implemented in JavaScript.
When using closures in JavaScript, you can think of them as a "nested" function. The inner function will have access to the outer function's variables, its own variables, and the global variables. The inner function has access to the outer function's parameters so that they can be quite powerful. After watching this video, can you name the inner function and outer function and describe how they work together?
The "scope" and "closures" in JavaScript can sometimes become intricate and confusing. This walk-through will step you through the basics of scope and talk about the scope chain and closures. This even steps into the more advanced concept of scope hoisting. You should try to work along with the video on these examples for a better understanding. This exercise does not count toward your grade. It is just for practice!
3.3: Using the "this" Keyword
The objective of this section is to extend your knowledge of the keyword
this
. Thethis
keyword in JavaScript references an object and is very powerful when used correctly.This video will explore how the
this
keyword functions in JavaScript. The most important thing to remember when working withthis
is what the function containing it is called. The value ofthis
changes depending on its calling context. For instance, if a function is called without an object reference, thenthis
refers to a global variable. On the other hand, if a function is called with an object reference, thenthis
refers to that specific object.In JavaScript, there is a way to call a function by using the
.call()
method. The syntax of the.call()
is as follows:functionName.call(thisArg, arg1, arg2, ….) //
arg1 and arg2 are optionalfunctionName:
Refers to the function being called and.thisArg
specifies the object thatthis
references inside the invoked function.Another way to invoke functions in JavaScript is using the
.apply()
method. The syntax for.apply()
is as follows:functionName.apply(thisArg, [array])
. "functionName
" refers to the function being called. However, with.apply()
, an array containing all values can be sent instead of individual arguments. Additionally, "thisArg
" specifies the object that "this" references inside the invoked function.The
bind()
method does not invoke a function but instead takes an existing function and creates a new function with a specified value for "this" inside the new function.The syntax of the
bind()
method is:bind(thisArg, arg1, arg2, ….) //
arg1 and arg2 are optionalThis example demonstrates a function invoked using
call()
andbind()
. Understanding how these methods usethis
and what values they will assign is essential. Working through these examples will give you insight into the various valuesthis
can take on.In JavaScript,
call()
andapply()
methods allow you to assign a customthis
value to your functions. Why might you want to do this? Well, using these methods can enable borrowing another object's methods. It is important to remember that the value ofthis
is assigned when a method or function is called and not defined. We recommend you watch this video and try the examples in your editor. Note that this exercise does not count toward your grade; it is just for practice!
3.4: Nested, Recursive, and High-Order Functions
Now you will learn more about JavaScript advanced functions and how to use them. Nesting functions and using functions for recursion are both advanced use of functions but are also helpful when coding certain algorithms.
Nested functions are much like nested loops. They occur when one function is nested inside the other. The inner function is private to the outer function. We discussed closures earlier – binding these variables with a closure allows nested functions to "inherit" the arguments and values of the other function. Understanding what function can access the other's variables is a unique relationship.
Recursion is when a function/method calls itself. It can be thought of as another way to loop or iterate. There are three ways in JavaScript that a function can refer to itself (call): 1. The function's name (it just calls its name); 2. arguments.callee; 3. An in-scope variable that refers to the function.
A classic recursion assignment is to do the factorial of a number. This video tutorial will show you how to write this program in JavaScript. Ensure your IDE is open and ready to work with this step-by-step guide.
Higher-order functions are functions that either take another function as an argument or return another function. JavaScript can become very powerful when you understand how to use these functions to help you write more powerful code. You use JavaScript's callback functionality when you pass a function as an argument.
This practice video shows you how to create a program that makes concentric circles using functions in JavaScript. It uses a loop to keep the circles drawing. For a challenge, change the loop into a recursive call once you have it working. This exercise does not count toward your grade. It is just for practice!
Unit 3 Assessment
- Receive a grade
Take this assessment to see how well you understood this unit.
- This assessment does not count towards your grade. It is just for practice!
- You will see the correct answers when you submit your answers. Use this to help you study for the final exam!
- You can take this assessment as many times as you want, whenever you want.