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]
- Expression Evaluation: The expression inside the brackets is evaluated and returned to the caller.
- List of Results: When returning multiple values, arrays or objects can be used to structure the data.
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.
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.
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.).
- The greet function returns a concatenated string 'Hello, ' with the provided name, creating a personalized greeting.
- The returned message is stored in the message variable and logged to the console, displaying the greeting.
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.
- The checkE function returns false if the number is odd.
- It returns true if the number is even.
Returning Objects, Arrays, and Functions
You can return complex data structures, such as objects, arrays, or even other functions.
Output{ name: 'Ishank', age: 30 }
- The createPerson function returns an object containing the name and age properties initialized with the given arguments.
- The object returned by the function is stored in the person variable, and when logged, it displays the person's details: { 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.
- The add function is an arrow function that returns the sum of two parameters, a and b.
- It is called with the arguments 3 and 4, and the result 7 is logged to the console.
Returning in Recursion
The return statement is essential in recursive functions to pass values back at each step of the recursion.
- The factorial function calculates the factorial of a number n recursively, returning 1 when n is 0.
- For the input 5, it recursively multiplies 5 * 4 * 3 * 2 * 1, returning the result 120.
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.
- The noRet function does not have a return statement, so it implicitly returns undefined.
- When called, undefined is logged to the console as the output.
Return Value Can Be Used in Expressions
The value returned from a function can be directly used in other expressions or operations.