Functions
This lesson explains JavaScript functions.
1. Reference Guide
Key topics
| Topic: | Definition |
|---|---|
| What are functions | We will go over what functions are and how to use them |
| Scope | We will go over what is scope and how it is used |
| Global and local variables | We will go over the difference between global and local variables |
| Recursive functions | We will go voer what recursive functions are |
Key vocab
| Term | Definition |
|---|---|
| Scope | Refers to the visibility and accessibility of objects |
| Local Variable | A variable that is declared inside a specific part of a program (in this case a function) |
| Global Variable | A variable called in the general code, has global scope |
| Recursve | In this context, it means the function is calling itself |
2. LxD Cycle Process
- Empathize
- Without functions, students would need to write out pieces of code multiple times
- This is prone to error
- With functions, tudents can just write the code once, and the call it multiple times
- Without functions, students would need to write out pieces of code multiple times
- Define
- Students would start off with not much knowledge of functions
- We plan on starting off with the basics before moving on to more complex parts of functions
- Students would start off with not much knowledge of functions
- Ideate
- We brainstormed ideas to make the lesson more fun and interactive
- We added some interactive code runners (Popcorn hacks) so that the students can apply what they have learned during lesson time
- This way, students can better remember what they have learned
- We brainstormed ideas to make the lesson more fun and interactive
- Prototyping
- We started off by changing some of the lesson and adding code runners
- We also made our own homework so that the student can showcase what they have learned
- Testing
- We showed our parents our lesson, and they gave us some feedback on how to improve our lesson
- We also showed it to Mr. Mortensen, who gave us a lot of feedback
- Ex. organizing our parts better, changing the code runners
3. Lesson Plan
Learning Objective: Use functions to call pieces of code multiple times, and be able to use scope and recursion
Success Criteria: You are able to create clean functions with no problem running them and be able to make a recursive function.
4. Tech talk
What are functions?
Functions are reusable blocks of code designed to perform specific tasks. Instead of writing the same pieces of code multiple times, you put it inside a function, which you can call whenever and can choose what goes in it.
Functions allow you to take a piece of code, and almost put it into a box so you can reuse it a lot of times. It also let you modularize code. For example, letβs look at the code below.
Code Runner Challenge
Check out this LONG piece of code!
View IPYNB Source
%%js
// CODE_RUNNER: Check out this LONG piece of code!
function rockPaperScissors() {
let myChoice = "rock";
let opponentChoice = "scissors";
let message = "Congratulations! You beat " + opponentChoice + " using " + myChoice + "!";
document.getElementById("output1").innerText += message;
myChoice = "paper";
opponentChoice = "paper";
message = "It's a tie because the opponent chose " + opponentChoice + " and you chose " + myChoice + "!";
document.getElementById("output1").innerText += "\n" + message;
myChoice = "scissors";
opponentChoice = "rock";
message = "Aw man! You got beat by " + opponentChoice + " when you chose " + myChoice + "!";
document.getElementById("output1").innerText += "\n" + message;
myChoice = "rock";
opponentChoice = "paper";
message = "Aw man! You got beat by " + opponentChoice + " when you chose " + myChoice + "!";
document.getElementById("output1").innerText += "\n" + message;
}
This code, while it works, has a lot of code that is reused. We can modularize this code as shown below.
Code Runner Challenge
Check out this WAY shorter version of the Rock Paper Scissors game!
View IPYNB Source
%%js
// CODE_RUNNER: Check out this WAY shorter version of the Rock Paper Scissors game!
function playRockPaperScissors(myChoice, opponentChoice){
let message;
if (myChoice === opponentChoice) {
message = "It's a tie because the opponent chose " + opponentChoice + " and you chose " + myChoice + "!";
} else if (
(myChoice === "rock" && opponentChoice === "scissors") ||
(myChoice === "paper" && opponentChoice === "rock") ||
(myChoice === "scissors" && opponentChoice === "paper")
) {
message = "Congratulations! You beat " + opponentChoice + " using " + myChoice + "!";
} else {
message = "Aw man! You got beat by " + opponentChoice + " when you chose " + myChoice + "!";
}
document.getElementById("output2").innerText += "\n" + message;
}
playRockPaperScissors("rock", "scissors");
playRockPaperScissors("paper", "paper");
playRockPaperScissors("scissors", "rock");
playRockPaperScissors("rock", "paper");
5. Popcorn hacks
Code Runner Challenge
Create a function that can greet someone by their name. The function should take a name as an argument and return a greeting message.
View IPYNB Source
%%js
// CODE_RUNNER: Create a function that can greet someone by their name. The function should take a name as an argument and return a greeting message.
function greet(name) {
}
More tech talk
Scope is a common pitfall for those learning functions. Press the button below to run the following code snippet.
Code Runner Challenge
Try seeing what the output of this code is!
View IPYNB Source
%%js
// CODE_RUNNER: Try seeing what the output of this code is!
function onClick() {
// myFunction() taken from W3Schools
function myFunction() {
let carName = "Volvo";
let text = "Inside (" + typeof carName + ") - " + carName;
document.getElementById("scope_demo2").innerHTML = text;
}
myFunction();
let text = "Outside - " + typeof carName;
document.getElementById("scope_demo1").innerHTML = text;
}
This is because of SCOPE!
Essentially, we have things called
- Local variables, and
- Global variables
Variables defined within a JavaScript function become LOCAL TO THAT FUNCTION.
If I define a variable called x inside of a function, it can only be accessed within that function. Even if we use var, it will remain stuck inside that function. You should avoid polluting the global scope.
Recursion
Recursion is where a function continuously calls itself. View the example below for a factorial recursion function:
Code Runner Challenge
Check out this recursive function!
View IPYNB Source
%%js
//CODE_RUNNER: Check out this recursive function!
function factorial(n) {
// If n is 0 or 1, the factorial is 1.
// This condition prevents infinite recursion.
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: the function calls itself with a smaller value of n.
else {
return n * factorial(n - 1);
}
}
For example we run factorial(5), it will do:
- factorial(5) = 5 * factorial(4), which calls:
- factorial(4) = 4 * factorial(3)
- factorial(3) = 3 * factorial(2)
- factorial(2) = 2 * factorial (1)
- factorial(1) = 1, where it stops
- So the final answer will be 5 * (4 * (3 * (2 * (1)))) which is 120 = 5!
Popcorn Hack 2
Code Runner Challenge
Create a function that takes a number and skip multiplies it (ex. if n=6, then it should multiply 6*4*2=48)
View IPYNB Source
%%js
// CODE_RUNNER: Create a function that takes a number and skip multiplies it (ex. if n=6, then it should multiply 6*4*2=48)
function skipMultiply(n) {
//add your code to make this a recursive function that skip multiplies here
}
6. Setup/Homework Hack
Create a new notebook in your portfolio homework area: _notebooks/homework.
Add one raw cell at the top with the frontmatter:
---
layout: post
codemirror: true
title: Functions HW
categories: [JavaScript]
lesson_language: JavaScript
lesson_topic: Functions HW
lesson_part: interactive
lesson_type: lesson
permalink: /js/functions/hw
author: <yourGithubID>
---
Add code cells for the Popcorn Hack and the Homework Hack. Make sure every cell runs with visible output.
Submit the link to your published page at the bottom of this page, and paste this in the description box:
Lesson: JavaScript Functions
Popcorn: function for skip multiplying and function for greeting someone
Homework: calculator that performs multiplication, division, subtraction, and addition
7. Grading Plan
Worth 1 point
| Part | Points | What earns the points |
|---|---|---|
| Popcorn hack 1 | 0.1 | Ability to enter a name and greet someone using the function |
| Popcorn hack 2 | 0.1 | Ability to enter any number and skip multiply |
| Homework hack | 0.8 | Addition (0.2 pts), subtraction (0.2 pts), multiplication (0.2 pts), and division (0.2 pts) functions work |
| Total | 1 | Β |
8. References
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
GeeksforGeeks: https://www.geeksforgeeks.org/dsa/introduction-to-recursion-2/
Submit Assignment
Self-Assessment
Rate your work on this assignment, then add a short reflection. All 5 fields are required before you can submit.
Need to update a submission later? Open the submissions dashboard.