Returning an Array from a JavaScript Function Made Easy

Guest Posts Paolo Nikko Nuñal

In the previous tutorial, we have manged to return two or more variables inside a function with the help of objects. This time around you are going to learn how to pass arrays from one function to another. This is also another common problem by many developers who wanted to pass array values rather than doing it variable by variable. Passing arrays in a function is easy and pretty much works the same way as variables.

Code


<script>
  var myArray = new Array();
  numbersArray(myArray);
  alert(myArray);
  function numbersArray(array){
      myArray[0] = "Toyota";
      myArray[1] = "Ford";
      myArray[2] = "Honda";
      myArray[3] = "Suzuki";

      return myArray;
  }
</script>


From the code above, you can see that we are passing the variable myArray to the function numbersArray that receives one parameter. After which, we put string variables on each index of the array and return the value of the myArray. Another example would be like this.

Code


<script>
    callFunction();
    function callFunction()
    {
        var dataArray = new numbersArray();
        alert(dataArray);
    }
    function numbersArray()
    {
       var myArray = new Array();


       myArray[0] = "Toyota";
       myArray[1] = "Ford";
       myArray[2] = "Honda";
       myArray[3] = "Suzuki";

       return myArray;
     }
</script>


In the second example we have declared dataArray as a variable that accepts whatever the numbersArray function returns. In our case, it creates an array and returns the array with populated data up to index 3.  After which we output the results in the alert.