Functions Return values
In JavaScript, functions can return values to the code that calls them, which allows you to use the result of the function in other parts of your code.
1. Basic Return
The return
statement ends a function's execution and specifies a value to be returned to the function caller.
In this example, the add
function returns the sum of a
and b
, which is then stored in the sum
variable.
2. Returning Different Data Types
A function can return any type of data: numbers, strings, objects, arrays, or even other functions.
3. Early Return
You can use the return
statement to exit a function early, which can be useful for validation or error handling.
4. Returning an Object
When returning multiple values, you can use an object to group them.
5. No Return Value (undefined)
If a function doesn’t explicitly return a value, it will return undefined
by default.
6. Returning a Function
JavaScript supports higher-order functions, meaning a function can return another function.
By understanding how to use return values, you can build more modular, reusable, and maintainable code in JavaScript.