INF-250: Web Design and Development — Functions, Parameters, and Return Values
Announcements
No in-person class next week (3/24, 3/26)
Keep up with your reading/videos. There is also a mini-assignment on Blackboard due next Sunday.
Quick Review
Over the last few classes, we built up the pieces needed to write real JavaScript programs. We learned how variables store values, how operators compare values, and how if/else statements let code respond to different situations.
This lecture focuses on the first part of that process: writing functions, passing values into them, getting values back out, and making basic decisions inside a function.
What a Function Actually Does
A function is a named block of code that performs a task. Functions let you avoid repeating the same instructions over and over again, and they give your code structure.
When you define a function, you give it a name and place the code inside curly braces. When you want the code to run, you call the function by using its name followed by parentheses.
function greetStudent() {
console.log("Welcome to INF-250!");
}
greetStudent();Defining Is Not the Same as Calling
A common beginner mistake is to define a function and then wonder why nothing happens. JavaScript only stores the instructions when the function is defined. The code does not run until the function is called.
function openClassMessage() {
console.log("Class has started.");
console.log("Open your browser console.");
}
// What is missing here?
// The function is defined, but it never runs.Functions with Parameters
A function becomes much more useful when it can accept information from outside. These inputs are called parameters.
Instead of writing one function for John and another for Sam, we can write one function that works with any student name and any course code.
function greetStudent(studentName, courseCode) {
console.log("Hello, " + studentName + "!");
console.log("Welcome to " + courseCode + ".");
}
greetStudent("John", "INF-250");
greetStudent("Sam", "INF-270");The parameter names are placeholders. When the function runs, JavaScript replaces them with the actual values you pass in.
Example: Add Another Parameter
If a function needs more information, add another parameter. Try finishing the function below so it also prints the student's role.
function createBadge(studentName, courseCode) {
console.log(studentName + " is in " + courseCode);
}
createBadge("Avery", "INF-250", "Designer");Returning Values from a Function
Sometimes a function should send a value back instead of only printing to the console. The return keyword sends a result back to the line of code that called the function.
This is the difference between a function that simply displays something and a function that helps us calculate something we want to reuse later.
function calculateTotal(score1, score2) {
return score1 + score2;
}
const totalScore = calculateTotal(18, 20);
console.log(totalScore); // 38Example: Why Is the Result Undefined?
Another common mistake is thinking that console.log() and return do the same job. They do not. Logging shows a value in the console, but return sends it back to the code that called the function.
function calculateAverage(score1, score2) {
const average = (score1 + score2) / 2;
console.log(average);
}
const result = calculateAverage(80, 90);
console.log("Average:", result);
// Why is result undefined?Using Conditions to Make Decisions
Once a function has a value to work with, we can make decisions inside it. This is where if and else statements become really useful.
In the example below, the function checks whether a score is high enough to pass. Notice that the function returns a different result depending on the condition.
function checkPassing(score) {
if (score >= 70) {
return "passing";
}
return "not passing";
}
console.log(checkPassing(82)); // "passing"
console.log(checkPassing(64)); // "not passing"Assignment Instead of Comparison
One of the easiest bugs to miss is using = when you meant to compare values. In a condition, = assigns a value. To compare, you usually want ===, >=, or another comparison operator.
function canSubmitProject(score) {
if (score = 70) {
return true;
}
return false;
}
console.log(canSubmitProject(85));
// Fix the condition so it checks the score correctly.Using the Console to Debug
When a function is not behaving the way you expect, add console.log() statements to inspect the value coming in. That helps you answer simple debugging questions: Did the function run? What value did it receive? Which branch of the condition did it use?
function canSubmitProject(score) {
console.log("Received score:", score);
if (score >= 70) {
return true;
}
return false;
}
console.log(canSubmitProject(85));Quick review: arrays
To define an array, use square brackets [] and separate the elements with commas.
const myArray = ["apple", "banana", "cherry"];
To access an element in the array, use its index inside square brackets. For example, myArray[0] gives you "apple". Remember that the first element has an index of 0.
const fruit1 = myArray[0];
const fruit2 = myArray[1];
To add an item to the end of an array, use the push() method.
myArray.push("grapes");
To add an item to the beginning of an array, use the unshift() method.
myArray.unshift("strawberry");
Group Work
Take a look at this rough "Mad-Libs" game. It asks users for certain types of words (noun, verb, adjective, etc) and outputs a story at the end using those words.
- Repository: https://github.com/padams-msj/mad-libs
Download it and open it up in VScode. I've started adding some basic functionality. But right now, nothing happens when the page loads.
- Get the game to actually start. Ideally, give the player some instructions and then a button to trigger the game.
- Add at least 8 prompts for different words.
- Return the words from
getWords()function as an array. - Pass those words (all in a single array) to the
createStory()function to generate the story. - Use
console.log()throughout your code to understand what is happening. - Add functionality that asks the player if they want to play again when done.
- Give it some CSS style!