Lab: JS Functions
- Defining and invoking functions
- Return values
(see page source code for the .html docs)
Task 1 - Coffee Calculations
Let's revisit the coffee calculator, and define some functions using code that we have previously written.
- Open the file
coffee.htmlin your editor. Examine the code.
Open the file
coffee.js. The function
calculateCoffeeCost()has been started for you in this file. The code should be familiar to you.
Define a second function
produceFeedback(amount)that takes as a parameter an amount, and returns the appropriate feedback regarding coffee consumption. As a reminder, the message should be:
- "That seems like a reasonable amount; enjoy!", for amounts less than $10,
- "Ok, that's a little pricey, but still not too bad.", for amounts from $10 to $30
- "Do you have any money left over for food?", for amounts $30 to $50, and
- "You'd better quit the habit before you go broke.", for more than $50 per week
- Open the JS console in your Chrome browser, and call the
produceFeedback()function: Just type its name, followed by a number in parens , in the console's prompt. This is a quick and easy way to call/invoke a function!
Test the function with different inputs to see that it works correctly.
- Invoke the
produceFeedback()function from within
calculateCoffeeCost()from the console to verify that the page works correctly.
- Now, instead of from the console, we will try to invoke
calculateCoffeeCost()as a response of the user clicking on a button:
- Add a responsive button to
<input type="button" value="Coffee Genie" onClick = "calculateCoffeeCost()">
- Reload the page after adding the button, and verify that the calculation occurs when the button is clicked.
Task 2 - Old MacDonald
old_mac.jsin your code editor, and
old_mac.htmlin your browser.
old_mac.htmlcarefully, to be sure you understand the structure and names of the elements on the page.
old_mac.js, write the function
produceVerse(animal,sound). This function should return a string which represents an entire verse of Old MacDonald.
produceVerse()from the console, using fixed values for the arguments, like:
You should see the string representing the HTML for the verse displayed in the console.
Add a second function
- reads the animal and the sound the user enters in the two input boxes, in the right part of the page,
- calls the
produceVerse()to produce the corresponding verse of the song, and add it to the
VersesIdarea in the left part of the page.
- reads the animal and the sound the user enters in the two input boxes, in the right part of the page, (like:
Click on the "Add Verse" button to test the function.
Add code to the
update_page()function to display on the page the list of the tests performed.
Add several verses to the song, and verify that the song and the tests are displayed on the page correctly.
- If time permits, add each pair of animal and sound to the