Welcome to the Function Return Tutorial!
Hey there, coders! In this tutorial, we're going to explore one of the most powerful features of JavaScript: function returns. By the end of this tutorial, you'll learn how to create a function that returns a value, and we'll use a real-world example to make it more engaging.
Let's get started!
Open your index.js
file and get ready to code!
Task: Create a function that takes a number as an input and returns its square.
Step 1: Define the function
Write the following code in your index.js
file:
function squareNumber(num) { // We'll fill this in later!}
What's happening here? We've defined a function called squareNumber
that takes one parameter, num
.
Step 2: Calculate the square Add the following code inside the function:
function squareNumber(num) { let square = num * num // We'll do something with `square` soon!}
What's happening here? We've calculated the square of the input number using the multiplication operator (*
).
Step 3: Return the result Add the following code inside the function:
function squareNumber(num) { let square = num * num return square}
What's happening here? We've used the return
statement to send the calculated square value back to the caller.
Step 4: Call the function and log the result Add the following code outside the function:
console.log(squareNumber(5)) // Try changing the input value!
What's happening here? We've called the squareNumber
function with an input value of 5
and logged the returned result to the console.
Run the code!
Click the "Run" button to execute the code. You should see the result 25
in the console.
Real-world example: Imagine you're building a calculator app, and you want to create a function that calculates the area of a square. This squareNumber
function would be a perfect fit!
What's next? In the next tutorial, we'll explore the concept of function scope. You'll learn how to use variables inside and outside functions.
You did it! You've successfully created a function that returns a value. Keep practicing, and you'll become a JavaScript master in no time!
Remember, the return
statement is a powerful tool in JavaScript. It allows you to send a value back to the caller, making your functions more flexible and reusable.
Happy coding!
Tests