Hello Developers, In this blog, we will learn how we can return multiple values from a function in javascript
First, create new JS file
1. By using an array.
You can simply return an array that contains multiple values
For Ex.
function getValues() { return [1, 2, 3]; } let arr = getValues(); console.log(arr[0]); // 1 console.log(arr[1]); // 2 console.log(arr[2]); // 3
2. By using an object.
You can simply return an object containing multiple values
For ex.
function getValues() { return { value1: 1, value2: 2, value3: 3 }; } let obj = getValues(); console.log(obj.value1); // 1 console.log(obj.value2); // 2 console.log(obj.value3); // 3
3. By using the destructor method.
function getValues() { return [1, 2, 3]; } let [a, b, c] = getValues(); console.log(a); // 1 console.log(b); // 2 console.log(c); // 3
4. By using the rest operator.
function getValues(...args) { return args; } console.log(getValues(1, 2, 3)); // [1, 2, 3]