Code highlights logo

Learn

Functions

Return Values

A return value is the data that a function sends back to the code that called it. It can be any valid data type such as numbers, strings, booleans, or even objects.

Returning Values from a Function

To return a value from a function, we use the return keyword followed by the value or expression we want to return. Once a return statement is executed, the function immediately stops executing and sends the value back to the caller.

Example:

1function calculateSum(a, b) {
2 return a + b;
3}

Using Return Values

Return values can be assigned to variables, used as inputs for other functions, or simply logged to the console for display. They provide a way for functions to communicate data back to the code that called them.

Example:

1let result = calculateSum(5, 3);
2console.log(result); // Output: 8

Multiple Return Statements

A function can have multiple return statements, but only one of them will be executed. The first return statement encountered in the function's execution path will be the one that sends the value back.

Example:

1function checkNumber(num) {
2 if (num > 0) {
3 return "Positive";
4 } else if (num < 0) {
5 return "Negative";
6 } else {
7 return "Zero";
8 }
9}

Instructions

1.

Inside the addNumbers function, add a return statement that returns the value of the sum variable.

Sign up to start coding

Already have an account?

Sign In

Course content