Functions Solutions

Warm Up

The purpose of this Warm Up is to illustrate that every application we use requires action - powered by JavaScript functions.

Try It: Declaring & Calling a Function

function sayHello() {
  console.log("hi");
  console.log("hey");
  console.log("hello");
}

sayHello();
//-> "hi"
//-> "hey"
//-> "hello"

function sayGoodbye() {
  console.log("byeeee");
  console.log("see ya");
  console.log("ciao");
}

sayGoodbye();
//-> "byeeee"
//-> "see ya"
//-> "ciao"

Medium Challenge: Did your sayHello sentences print before or after your sayGoodbye sentences? Why?

  • As they are currently written above, the sentences from sayHello will all print out first. That function is called first, or on a line of code higher in the file than, sayGoodbye.
  • Each time a function is called, it will do it’s entire job, from start to finish, before the next line of code is run!

Try It: Arguments & Parameters

Mild Challenge: Write a function that will take 1 argument when called, a number. The function should console.log the sum of that number and 5. Make sure to name your function something related to its job.

function addToFive(num) {
  var sum = num + 5;
  console.log(sum);
}

addToFive(3);
//-> 8

addToFive(12);
//-> 17

Medium Challenge: Write a function that will take 2 arguments when called, both being numbers, and that will console.log the sum of those two numbers. Make sure to name your function something related to its job.

function addTwoNumbers(firstNum, secondNum) {
  var sum = firstNum + secondNum;
  console.log(sum);
}

addTwoNumbers(3, 6);
//-> 9

addTwoNumbers(8, 12);
//-> 20

Spicy Challenge: Write a function that will take 3 arguments when called, all being numbers. It should sum the first two numbers, then multiply that sum by the third number and console.log the result. Make sure to name your function something related to its job.

function sumAndMultiply(firstNum, secondNum, multiplier) {
  var sum = firstNum + secondNum;
  var final = sum * multiplier;
  console.log(final);
}

sumAndMultiply(3, 6, 2);
//-> 18

sumAndMultiply(8, 12, 3);
//-> 60

Turn & Talk

With your partner, read through each line of the code above. With as much technical vocabulary as possible, explain what is happening at each line.

Scholars may not know every line of this, but it’s a good opportunity to identify which parts they do know well. The point is to explore the concept of return values, and the next section of the lesson has an explicit review of that concept. If you identify that they need review on arguments/parameters or anything else entailed here, this is a great time to stop and clear up any misconceptions!

function timeToWalk(numberOfDogs) {     //declare a function called timeToWalk
                                        //timeToWalk is declared with 1 parameter  
  var totalMinutes = numberOfDogs * 15; //declare a variable called totalMinutes
                                        //which stores the product of 15 and
                                        //numberOfDogs which was the argument passed in
  return totalMinutes;                  //return the value (Number) out of the function
}

var minutes = timeToWalk(3);            //call the function timeToWalk, passing in an
                                        //argument of 3, and storing the return value in
                                        //the minutes variable
console.log(`You should walk a total of ${minutes} minutes.`);
//print out a sentence that interpolates the value in the minutes variable

Try It: Logic Inside a Function

Write a function that takes one argument, a gradeLevel. It should then print out “You are in elementary school” or “You are in middle school”, etc. based on the grade level passed in.

function schoolAttended(gradeLevel) {
  if (gradeLevel < 6) {
    console.log("Your are in elementary school.");
  } else if (gradeLevel < 9) {
    console.log("You are in middle school.");
  } else  {
    console.log("You are in high school.");
  }
}

schoolAttended(3);
//-> "Grade 3 is in elementary school."

A more advanced solution:

function schoolAttended(gradeLevel) {
  if (gradeLevel > 1 && gradeLevel < 6) {
    console.log("Grade ${gradeLevel} is in elementary school.");
  } else if (gradeLevel > 5 && gradeLevel < 9) {
    console.log("Grade ${gradeLevel} is in middle school.");
  } else if (gradeLevel > 8 && gradeLevel < 13) {
    console.log("Grade ${gradeLevel} is in high school.");
  }
}

schoolAttended(3);
//-> "Grade 3 is in elementary school."

Now, write another function that takes in a number, a dogAge, and multiplies it by 7. It should print out a sentence telling the dog how old it is in human years.

function humanYears(dogAge) {
  var humanAge = dogAge * 7;
  console.log(`You are ${humanAge} years old in human years.`)
}

humanYears(4);
//-> "You are 28 years old in human years."

Practice: Functions, Arguments, Return Values

Brainstorm

Task: Make cereal

Steps:

  • Get out a bowl and spoon from cabinet
  • Get out milk from fridge, get out cereal from pantry
  • Pour cereal in bowl
  • Pour milk
  • Put milk back in fridge
  • Put cereal back in pantry
  • Put spoon in cereal, enjoy!

Possible Arguments: type of cereal, type of milk, size of bowl, size of spoon

// first round, no return value
function makeCereal(cereal, milk) {
  console.log(`Get out a spoon and bowl.`);
  console.log(`Get out the ${milk} milk and the box of ${cereal}.`);
  console.log(`Pour ${cereal} in bowl, then the milk.`);
  console.log(`Put ${cereal} and milk away.`);
  console.log(`Put spoon in cereal.`);
  console.log(`Enjoy!`);
}

makeCereal("Cinnamon Toast Crunch", "2%");

//second round, with return value
function makeCereal(cereal, milk) {
  console.log(`Get out a spoon and bowl.`);
  console.log(`Get out the ${milk} milk and the box of ${cereal}.`);
  console.log(`Pour ${cereal} in bowl, then the milk.`);
  console.log(`Put ${cereal} and milk away.`);
  console.log(`Put spoon in cereal.`);
  return `Enjoy your ${cereal} with ${milk} milk.`
}

var breakfast = makeCereal("Cinnamon Toast Crunch", "2%");
console.log(breakfast);
//-> "Enjoy your Cinnamon Toast Crunch with 2% milk."