3.12 Calling Procedures Homework in JavaScript

Complete the 4 tasks below as homework:

  1. Create the functions
  2. Run the Code cell
  3. Have fun!

Hack — Example 1: Simple function with no parameters

// TODO: Call sayHello to print "Hello there!"
function sayHello() {
    
}
// sayHello();
  • Does the code run as expected?
  • If yes, move on to the next hack.

Hack — Example 2: Function with one parameter

// TODO: Call greet with your name to welcome the student
function greet(name) {
    
}
// greet('_____');
  • Does your code properly greet the person?
  • Are there no errors in your code?
  • If yes, move on to the next hack.

Hack — Example 3: Function with two parameters

// TODO: Call addNumbers with two numbers to print their sum
function addNumbers(a, b) {
    
}
// addNumbers(_, _);
  • Does addNumbers(3, 7) give 10?
  • Does it work for other numbers too?
  • If yes, move on to the next hack.

Hack — Example 4: Function that returns a value

// TODO: Implement factorial(n) to return n!
function factorial(n) {
    
}
// Example: factorial(5) should return 120
// const result = factorial(_);
  • Does factorial(0) return 1?
  • Does factorial(1) return 1?
  • Does factorial(5) return 120?
  • If yes, move on to the next hack.

Hack - Challenge Example 5: Function calling another function

// Dictionary (object) of items and their prices
const storeItems = {
  apple: 1.25,
  banana: 0.75,
  milk: 3.5,
  bread: 2.0
};

// Function 1: calculate subtotal
function getSubtotal(cart) {
  /*
    Takes an object of items (item: quantity)
    and returns the total before tax.
  */
  let subtotal = 0;
  // TODO: for each item in cart:
  // - find its price in storeItems
  // - multiply by quantity
  // - add to subtotal
  return subtotal;
}

// Function 2: add tax
function addTax(subtotal, taxRate) {
  /*
    Takes subtotal and tax rate (like 0.08 for 8%)
    and returns the total with tax.
  */
  // TODO: calculate total with tax and return it
  return 0; // placeholder
}

// Function 3: checkout
function checkout(cart, taxRate) {
  /*
    Calls getSubtotal() and addTax()
    to print subtotal and final total.
  */
  // TODO: get subtotal using getSubtotal(cart)
  // TODO: get total using addTax(subtotal, taxRate)
  // TODO: log both subtotal and total
}

// Example cart for testing
const myCart = {
  apple: 2,
  milk: 1,
  bread: 1
};

// TODO: call checkout(myCart, 0.08)

  • If the shopping cart contains 2 apples, 1 milk, and 1 bread, will your program show a subtotal of $8.00 and a total of $8.64 with an 8% tax rate?
  • Try changing the cart to 3 bananas and 2 milk — should the subtotal be $10.25 and the total with 8% tax be $11.07?
  • If your output matches these totals, your function calls and calculations are correct!