Working with Functions
How to declare a JavaScript function, which names no return type and no parameter types.
Apprentice · JavaScript · Updated
JavaScript functions work like Java functions but they are declared differently.
// this function adds two numbers and returns the value
function add(first, second)
{
return first + second;
}
// this function DOES NOT return a value
function displayMessage(message)
{
console.log(message);
}
Notice that a JavaScript function names no return type, and its parameters name no data types. This is because JavaScript is dynamically typed. You can pass any type of value, or leave arguments out, and JavaScript allows it (a missing argument is undefined).
Do it: add up a snack order
The snack stand's menu script needs to know what an order costs. Most orders are for one snack, so the menu often calls the function with only the price.
The function gets two values:
price: the price of one snack, a number, such as2.5.quantity: how many of that snack were ordered, such as4. A call can leave it out, and then the order is for1snack.
For example, snackTotal(2.5, 4) returns 10: 2.5 × 4. And snackTotal(3) returns 3: the quantity was left out, so it's 1 snack at 3.
Your job: write the function snackTotal(price, quantity).
- Return the price times the quantity.
- When a call leaves out
quantity, use1. - A
quantityof0is a real quantity:snackTotal(1.25, 0)returns0.
Practiced live on the lesson page: write the JavaScript right there and check it.