How to pass arrays as function arguments in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Passing arrays as function arguments

In olden days if we need to pass arrays as function arguments then apply() and null should be used. The use of null makes a code unclean. So to make code clean and also to pass an array as a function argument, the spread operator comes in to picture. By using the spread operator we don't need to use apply() function. Lets' discuss it in a nutshell.

Example

In the following example, we have used null and apply() to pass an array as a function argument. This is an obsolete method. This method is replaced by a modern method in which spread operator is used.

Live Demo

<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar.apply(null, names);
</script>
</body>
</html>

Output

NSE
BSE
NIFTY

If we observe the following example, apply() function and null weren't used, instead of those ES6 spread operator is used. The use of spread operator makes the code urbane and there is no need to use useless null value.

Example

Live Demo

<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar(...names);
</script>
</body>
</html>

Output

NSE
BSE
NIFTY
raja
Published on 03-Jul-2019 08:47:28
Advertisements