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.
function add(a, b) {return a + b;}const sum = add(3, 5); // sum is now 8console.log(sum); // Outputs: 8
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.
function greet(name) {return "Hello, " + name;}console.log(greet("Amir")); // Outputs: Hello, Amir
3. Early Return
You can use the return
statement to exit a function early, which can be useful for validation or error handling.
function divide(a, b) {if (b === 0) {return "Cannot divide by zero";}return a / b;}console.log(divide(10, 2)); // Outputs: 5console.log(divide(10, 0)); // Outputs: Cannot divide by zero
4. Returning an Object
When returning multiple values, you can use an object to group them.
function getUserInfo() {return {name: "Amir",age: 30};}const userInfo = getUserInfo();console.log(userInfo.name); // Outputs: Amir
5. No Return Value (undefined)
If a function doesn’t explicitly return a value, it will return undefined
by default.
function logMessage() {console.log("This is a message");}const result = logMessage(); // result is undefinedconsole.log(result); // Outputs: undefined
6. Returning a Function
JavaScript supports higher-order functions, meaning a function can return another function.
function createMultiplier(multiplier) {return function (value) {return value * multiplier;};}const double = createMultiplier(2);console.log(double(5)); // Outputs: 10
By understanding how to use return values, you can build more modular, reusable, and maintainable code in JavaScript. Let me know if you’d like to dive deeper into a specific use case or concept!