Skip to content

JavaScript function array parameter | Example code

  • by

Use the apply() method to use the array as a parameter in the JavaScript function.

const args = ['p0', 'p1', 'p2'];
function_name.apply(this, args);

If the environment supports ECMAScript 6, you can use a spread argument instead. The spread operator can do many other useful things.

call_me(...args);


In JavaScript, you can pass an array as a parameter to a function just like any other variable. The array can then be manipulated or used within the function. Here’s a simple example:

// Function that takes an array as a parameter and logs each element
function logArrayElements(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}

// Example usage
const myArray = [1, 2, 3, 4, 5];
logArrayElements(myArray);

JavaScript function array parameter

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>

   const args = ['p0', 'p1', 'p2'];
   call_me.apply(this, args);

   function call_me (param0, param1, param2 ) {
    console.log(param0, param1, param2)
  }
</script>

</body>
</html> 

Output:

JavaScript function array parameter

Can also use spread:

function foo(a, b, c, d){
  console.log(a, b, c, d);
}

foo(...[1, 2, 3], 4)

Output: 1 2 3 4

function print(...inpu){
console.log(...inpu)
}
var arry = ['p0','p1','p2']
print(...arry)

You can also modify the array within the function, and changes will be reflected outside the function because arrays in JavaScript are passed by reference. For example:

// Function that adds 1 to each element of the array
function addOneToElements(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] += 1;
  }
}

// Example usage
const myArray = [1, 2, 3, 4, 5];
addOneToElements(myArray);

console.log(myArray); // Output: [2, 3, 4, 5, 6]

In this example, the addOneToElements function modifies each element of the array by adding 1 to it. When you later log the original array, you can see that it has been changed.

Do comment if you have any doubts or suggestions on this JS function code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *