Function Inputs and Outputs
You already know how to create and call basic functions.
Now you will learn how the same function can work with different values and send a result back to your code.
Inputs: parameters and arguments
A function input is a value that a function receives when it runs.
In JavaScript, we use two important words for function inputs: parameters and arguments.
A parameter is a placeholder name inside the function definition.
An argument is the real value you pass into the function when you call it.
First code example
function greetUser(firstName) {
console.log("Hello, " + firstName + "!");
}
greetUser("Alice");
greetUser("Bob");Code walkthrough
In this example, firstName is the parameter. It works like an empty slot inside the function.
When we write greetUser("Alice"), "Alice" is the argument. JavaScript puts "Alice" into the firstName slot and creates the greeting.
When you click Run, you will see two greetings in the Output section.
Outputs: using return
Sometimes a function should calculate a value and send the result back to the rest of your code.
To do that, use the return keyword.
When JavaScript reaches return, the function stops running and sends a value back to the place where the function was called.
You can store that returned value in a variable.
function calculateTotal(price, tax) {
return price + tax;
}
const finalPrice = calculateTotal(10, 2);
console.log("Your total is: " + finalPrice);return vs console.log()
console.log() sends a value to the Output section so you can see it.
return sends a value back to your code so the program can save it and reuse it.
In the example above, calculateTotal(10, 2) returns 12. Then 12 is stored in the finalPrice variable.
Finally, console.log() shows the final message in the Output section.
Mini task
Edit the calculateTotal example above.
Change the arguments inside calculateTotal(10, 2) to find the total for a price of 20 and a tax of 5.
Click Run to view your new total in the Output section.
Short quiz
Question: What is the difference between a parameter and an argument?
Answer: A parameter is the placeholder name in the function definition. An argument is the real value passed into the function when it is called.
Small challenge
Write a function named getScore.
The function should take two parameters: points and bonus.
Inside the function, return the sum of those two numbers.
Then call your function with real arguments, save the result in a variable, and print that variable.
// put your code below
console.log()Summary
- A parameter is a placeholder inside a function definition.
- An argument is a real value passed into a function call.
returnsends a value back from a function.console.log()shows a value in the Output section.- Returned values can be stored in variables and reused later.