Return Types in JavaScript Function

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.    
  12.         </script>  
  13. </body>  
  14. </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.    
  8.             function hello() {  
  9.                 var student = new Object();  
  10.                 student.name = "Rama";  
  11.                 student.surname = "Sagar";  
  12.                 return student;  
  13.             }  
  14.               
  15.             var p = hello();  
  16.             alert(p.name + " " + p.surname);  
  17.    
  18.    
  19.         </script>  
  20. </body>  
  21. </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.    
  9.             function fun() {  
  10.                 return '{"name":"Rama","surname":"Sagar"}';  
  11.             }  
  12.             var value =JSON.parse(fun());  
  13.             alert(value.name + value.surname);  
  14.    
  15.    
  16.         </script>  
  17.     </form>  
  18. </body>  
  19. </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.

Up Next
    Ebook Download
    View all
    Learn
    View all