Lesson 12 - Function Return Values in JavaScript
As blocks of code that execute a specific logic, the outcome of such process can be immediately displayed or simply return for us to decide what to do with it. This aspect of returning a certain value from functions make them elegant to use.
Let's look at how to achieve that in JavaScript.
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log("The sum is: " + sum);
Explanation:
- Functions can return values using the
return
keyword. add(a, b)
takes two numbers, adds them, and returns the result.- When we call
add(5, 3)
, itreturns 8
, which is then stored insum
and printed.
Try your hand
1. Create a File:
Create a new file named lesson12-return-function.html
.
2. Write the Code:
Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 12 - Function Return</title>
</head>
<body>
<script>
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log("The sum is: " + sum);
</script>
</body>
</html>
Save the file in your folder.
3. Preview the File:
- Open the file in your browser and access the developer console.
- Observe the output:
The sum is: 8
4. Experiment:
- Change
add(5, 3)
toadd(10, 7)
and observe the new sum. - Modify the function to subtract instead of adding:
function subtract(a, b) {
return a - b;
}
console.log(subtract(10, 4)); // Output: 6
- Try returning a string:
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("David")); // Output: Hello, David!