Hey there, coder!
Welcome to our tutorial on Function Parameters in JavaScript! Today, we're going to create a function that calculates the area of a rectangle. Sounds like a great real-world problem, right?
Before we dive in, let's review what you've learned so far. You've mastered Output Statements, Variables and Data Types, Template Literals, Arithmetic Operations, Boolean Logic, If Statements, Switch Statements, Arrays, Objects, Loops, and Functions! You're doing great!
Now, let's get started with Function Parameters!
Step 1: Create a function with parameters
In your index.js
file, write the following code:
function calculateArea(length, width) { // we'll fill this in soon!}
Here, we've created a function called calculateArea
that takes two parameters: length
and width
. These parameters will represent the length and width of our rectangle.
Step 2: Calculate the area
Now, let's calculate the area of the rectangle inside our function. Remember, the formula for the area of a rectangle is area = length * width
. Update your code as follows:
function calculateArea(length, width) { const area = length * width console.log(`The area of the rectangle is ${area} square units.`)}
Here, we've calculated the area by multiplying length
and width
, and logged the result to the console using a Template Literal.
Step 3: Call the function with arguments
Now, let's call our calculateArea
function with some sample values. Add the following code:
calculateArea(5, 3)
Here, we're calling calculateArea
with length = 5
and width = 3
.
Step 4: Run the code
Click the "Run" button to execute your code. You should see the following output in the console:
The area of the rectangle is 15 square units.
Whoa! Our function worked!
What's happening behind the scenes?
When we called calculateArea(5, 3)
, the values 5
and 3
were passed as arguments to our function. These arguments were then assigned to the length
and width
parameters, respectively. Our function then used these values to calculate the area of the rectangle.
Function Parameters Recap
Function parameters are values that are passed to a function when it's called. In our example, length
and width
are parameters that are used to calculate the area of a rectangle. By using parameters, we can make our functions more flexible and reusable.
That's it for today! You've learned how to use Function Parameters to create a reusable function that calculates the area of a rectangle. In our next tutorial, we'll explore Function Return values.
Keep coding, and I'll see you in the next tutorial!
Tests