Introduction

In this article, we will learn about return types of functions in JavaScript. JavaScript arrays are used to store multiple values in a single variable.

Return Boolean Type

We can return any predefined data type like Boolean, string, array, and many more. Here the hello() function returns a Boolean value. Here is the sample code.
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4. </head>
  5. <body>
  6. <script>
  7. function hello() {
  8. return true;
  9. }
  10. alert(hello());
  11. </script>
  12. </body>
  13. </html>

Return Object from Function

We can return an object from a JavaScript function. In this example we are returning a “person” object from the hello() function and then we are showing the return value. Here is a sample example.
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4. </head>
  5. <body>
  6. <script>
  7. function hello() {
  8. var student = new Object();
  9. student.name = "Rama";
  10. student.surname = "Sagar";
  11. return student;
  12. }
  13. var p = hello();
  14. alert(p.name + " " + p.surname);
  15. </script>
  16. </body>
  17. </html>

Return JSON Data

We can return JSON data from a function and then parse it. In this example the fun() function returns JSON data. The JSON data contains two key value pairs called name and surname.
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <script>
  8. function fun() {
  9. return '{"name":"Rama","surname":"Sagar"}';
  10. }
  11. var value =JSON.parse(fun());
  12. alert(value.name + value.surname);
  13. </script>
  14. </form>
  15. </body>
  16. </html>

Summary

In this article, we learned various return types of JavaScript functions. In a future article, we will learn some more basic concepts of JavaScript.