JavaScript Functions - Returning Values


JavaScript functions allow you to perform actions and return values. In this guide, we'll explore how to create functions that return values and provide examples to illustrate their usage.


Creating Functions with Return Values


To create a function that returns a value, use the return statement followed by the value you want to return:


function add(a, b) {
return a + b;
}
const result = add(5, 3); // Calling the function and storing the result

Using Return Values


Returned values can be used in various ways, such as assigning them to variables or using them directly in expressions:


const sum = add(7, 2); // Storing the result in a variable
const product = add(4, 6) * 2; // Using the result in an expression

Multiple Return Statements


A function can have multiple return statements, but only one will be executed. This allows you to conditionally return values:


function isEven(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}
const even = isEven(6);
const odd = isEven(5);

Returning Complex Values


Functions can return complex data types, such as objects, arrays, or other functions:


function createPerson(firstName, lastName) {
return {
first: firstName,
last: lastName
};
}
const person = createPerson("John", "Doe");

Default Return Values


If a return statement is omitted in a function, it will return undefined by default:


function doSomething() {
// No return statement, function returns undefined
}
const result = doSomething(); // result will be undefined

Conclusion


Returning values from functions is a fundamental concept in JavaScript. By understanding how to create functions that return values, you can write reusable code and perform calculations or operations that produce meaningful results in your applications.


Happy coding!