JavaScript Return Statement (original) (raw)

Last Updated : 07 Feb, 2025

The return statement in JavaScript is used to end the execution of a function and return a value to the caller. It is used to control function behaviour and optimise code execution.

**Syntax

return [expression]

How does the Return Statement Work?

The return statement stops function execution and returns a value to the caller. If no value is specified, the function returns undefined by default.

JavaScript `

function add(a, b) { return a + b; }

const res = add(5, 10); console.log(res);

`

In this example, the return statement returns the sum of a and b to the caller.

Using Return Without a Value

If a return statement is used without a value, the function will return undefined.

JavaScript `

function noReturn() { return; }

console.log(noReturn());

`

Returning Value from function

You can return values from a function using the return statement, and these values can be of any type (number, string, object, etc.).

JavaScript `

function greet(name) { return 'Hello, ' + name; } let message = greet('Pranjal'); console.log(message);

`

Exiting a Function Early

The return statement can be used to exit from a function early when a condition is met, skipping the remaining code.

JavaScript `

function checkE(number) { if (number % 2 !== 0) { return false; } return true; } console.log(checkE(4)); console.log(checkE(5));

`

Returning Objects, Arrays, and Functions

You can return complex data structures, such as objects, arrays, or even other functions.

JavaScript `

function Person(name, age) { return { name: name, age: age }; } let person = Person('Ishank', 30); console.log(person);

`

Output

{ name: 'Ishank', age: 30 }

Returning from Arrow Functions

Arrow functions simplify returning values. If there is only one expression, the return keyword and curly braces can be omitted.

JavaScript `

const add = (a, b) => a + b; console.log(add(3, 4));

`

Returning in Recursion

The return statement is essential in recursive functions to pass values back at each step of the recursion.

JavaScript `

function factorial(n) { if (n === 0) { return 1; } return n * factorial(n - 1); } console.log(factorial(5));

`

No return vs return undefined

If a function doesn't include a return statement, it returns undefined by default. However, explicitly using return undefined returns the value undefined.

JavaScript `

function noRet() { } console.log(noRet());

JavaScript

function retUn() { return undefined; } console.log(retUn());

`

Return Value Can Be Used in Expressions

The value returned from a function can be directly used in other expressions or operations.

JavaScript `

function square(x) { return x * x; } console.log(square(2) + 10);

`

Best Practices for Using Return Statement