Multiple return values. Some functions return just one value—they return a string or an integer. But others functions in Node.js return many things—an assortment of values.
Return notes. With an array, or an object, we can return multiple values. We can return any number of values from a function, but special syntax is needed.
function importantValues() {
// Return 3 values in an array.
return [1, 2, "cat"];
}
var result = importantValues();
console.log("RETURN VALUE 1: " + result[0]);
console.log("RETURN VALUE 2: " + result[1]);
console.log("RETURN VALUE 2: " + result[2]);RETURN VALUE 1: 1
RETURN VALUE 2: 2
RETURN VALUE 2: cat
Object. With an object we can reference return values by name. This approach may be clearer to read. The return values are labeled.
Tip In the V8 engine a special optimization is used to accelerate property lookups, so this approach is blazingly fast.
function petValues() {
// Return multiple values in an object.
return {animal: "cat",
size: 100,
color: "orange",
name: "fluffy"};
}
var pet = petValues();
console.log("RETURN VALUE: " + pet.animal);
console.log("RETURN VALUE: " + pet.size);RETURN VALUE: cat
RETURN VALUE: 100
Strict mode. As a reminder, the "use strict" directive can prevent errors in functions. It can help us avoid "sloppy" global variable creation in functions.
Summary. Programs written in Node.js have many powerful features—functions can use multiple return values. We can use arrays or objects.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.