Return Values

In JavaScript, functions can send back a value after they finish running. This value is called the return value. It allows the function to output a result that can be used elsewhere in your code.

Illustration of return_values
Illustration of return_values

💡 What is a Return Value?

A return value is the output a function produces, which you can assign to variables or use in expressions.

To specify a return value, use the return keyword followed by the value you want to send back.

📌 Deep Dive: Returning a Value from a Function

JAVASCRIPT
function square(num) {
  return num * num;
}

const result = square(4);
console.log(result); // 16
Output
16

If a function does not explicitly return a value, it returns undefined by default.

⚠️ No Return Means Undefined

Functions without a return statement return undefined. This can lead to bugs if you expect a value.

📌 Deep Dive: Function Without Return

JAVASCRIPT
function greet(name) {
  console.log('Hello, ' + name);
}

const greeting = greet('Alice');
console.log(greeting); // undefined
Output
Hello, Alice undefined

You can return any type of value: numbers, strings, objects, arrays, functions, or even other functions.

Examples of Return Values
Returned ValueExample
Numberreturn 42;
Stringreturn "Hello";
Arrayreturn [1, 2, 3];
Objectreturn {name: "Alice"};
Functionreturn function() { return 5; };

You can also use return without a value to immediately exit a function.

📌 Deep Dive: Early Return to Exit Function

JAVASCRIPT
function checkAge(age) {
  if (age < 18) {
    return; // exits function early
  }
  console.log('Access granted');
}

checkAge(16); // no output
checkAge(21); // Access granted
Output
Access granted

💡 Summary

  • The return statement sends a value back from a function.
  • Without return, functions return undefined.
  • You can return any type of data.
  • Using return also stops function execution immediately.