Returning Values from Functions
Functions in JavaScript can not only perform actions but also return values back to the place from where they were called. This is very useful when we want to process or use the result of an operation. To return a value from a function, we use the return
keyword. For example:
function add(a, b) {
return a + b;
}
const result = add(3, 4);
console.log(result); // Prints: 7
This function add
has two arguments, which it adds and returns using the return
keyword. We then assign this returned value to the variable result
, which we subsequently print. It is also important to note that returning a value ends the execution of the function. For example:
function rectangleArea(a, b) {
if (a < 0 || b < 0) {
return "Side lengths cannot be negative!";
}
return a * b;
}
const result = rectangleArea(3, 4);
console.log(result); // Prints: 12
const result2 = rectangleArea(-3, 4);
console.log(result2); // Prints: Side lengths cannot be negative!
This function rectangleArea
takes two arguments (rectangle side lengths) a
and b
and returns the text "Side lengths cannot be negative!"
if any side length is negative. When this happens, the value is returned, and the rest of the function is not executed (return a * b
is not executed). If no side length is negative, the function returns the area of the rectangle using return a * b
. We store the returned value in the variable result
, which we then print.
Instructions
Complete the function subtract
to return the difference (a-b).
Start programming for free
6/7