function JavaScript

function JavaScript

A quick guide to passing array to function in javascript with example. As a beginner, we often tend to stuck with the basics.

Thus, we at Letstacle try to help students to learn and code in JavaScript and many other programming languages.

What are functions or methods in JavaScript?

A self-contained block of code that performs a specific task is called function/methods.

These methods allow us to break up large and complex chunks of calculations that may involve many lines of code into more manageable units.

How to pass an array to a function in JavaScript?

You can pass an array to a function in JavaScript in the same way you do in any other programming language like Java and C++. That is to say, by writing the function name and simply passing the array in the ( ) parenthesis.

pass array to function example

pass array to function example

Note: As JavaScript is a loosely typed language you don’t need to write array then square brackets [].  Simply write the array name inside the function call, see the syntax below-

// syntax function call and passing a array
functionName(arrayName);

Let’s take an example of a JavaScript function that takes an array as the parameter and returns the array after processing it.

For Example: Pass an array of numbers to a function in Javascript and return an array such that the number are arranged in ascending order.

Given Array: [3, 4, 1, 9, 0, 7, 6, 2, 8, 5, 10]


// define a function to sort array in ascending order
function ascendingOrder(array) {
  let temp = 0;
  for (let i = 0; i < array.length; i++) {
    for (let j = i + 1; j < array.length; j++) {
        temp = array[i]; 
        if (array[i] > array[j]) {
        array[i] = array[j];
        array[j] = temp;
      }
    }
  }
  return array;
}

// Our given array that needs to be sort
let array = [3, 4, 1, 9, 0, 7, 6, 2, 8, 5, 10];

// calling the fucntion by passing the given array
let output = ascendingOrder(array);

// show the returned output on console 
console.log(output);

After that, at  line number 20, we are making a function call by passing the array and storing the returned array in the output variable.

The output on the console is below-

Passing Array to function in JavaScript Example

retuned array and output on JavaScript console

Finally, As you can see we have successfully passed an array to the javaScript function ascendingOrder(). And the passed array is sorted in ascending order and logged to the console for display output.

In conclusion, hope you have learned Passing Array to function in JavaScript Example.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed