TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVASCRIPT

JavaScript Multiple Return Values

Return multiple values from a function with an array and an object in a single statement.
Multiple return values. Some functions return just one value. They return a string. They return an integer. But others return many things—an assortment of values.
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.ArrayObject
Array example. An array can hold any number of elements. We can return an array from a function. We put our multiple return values in the array.

Function: The importantValues function returns an array of 3 values. These could be computed variables or constants.

function
JavaScript program that returns multiple values function importantValues() { "use strict"; // 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]); Output 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.

JavaScript program that sets properties on object function petValues() { "use strict"; // 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); Output 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.
A summary. JavaScript is a powerful language—it can handle complex patterns like multiple return values. We can use arrays or objects.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf