![]() |
VOOZH | about |
In JavaScript, the return statement is used to specify the value that a function should produce when it is called. It helps in controlling the flow of execution and provides meaningful outputs from functions. Understanding how return works is important for writing efficient and reusable code.
The return statement in JavaScript is used to end a function execution and send a value back to where the function was called. It allows the function to provide useful results, like numbers, strings, or objects, that can be used in other parts of the code.
If there’s no value after return, the function will return undefined by default. The return statement also stops the function’s execution, meaning no further code inside the function will run once it’s called.
Syntax
return [value];'value' is the data you want to return from the function. If no value is specified, the function returns undefined by default
When a return statement is executed in a function, the function exits immediately. Any code written after the return statement is ignored.
Hello, GFG
Functions in JavaScript can return values. This is essential when you need to calculate or process data inside a function and return the result to the caller.
8
In JavaScript we can also return object from a function this is a special type of behavior of JavaScript as each and every thing in JavaScript is an object.
{ name: 'Pranjal', age: 21 }
In JavaScript we can also return arrays from a function because arrays are also converted into objects at last as Object is the top level hierarchy in JavaScript.
[ 1, 2, 3, 4 ]
In JavaScript, functions are first-class citizens, meaning they can be returned from other functions.
Hello from the inner function!
In JavaScript, arrow functions allow you to return a value automatically without using the return keyword, making the code shorter and easier to write for simple functions.
5
In recursive functions, return plays a vital role in terminating the recursion and passing the result back through the recursive calls.
24
In JavaScript, some functions may not return any value explicitly, meaning they return undefined by default. These functions can still perform actions like logging or modifying data.
This function does not need a return value
If no return statement is provided in a function, the function returns undefined by default.
undefined
In summary, the return statement is essential in JavaScript functions, allowing them to send values back to the caller. It improves code reusability, readability, and efficiency by enabling function chaining and early exits. Understanding how to use return effectively helps write cleaner and more flexible code.