JS Dasar: 48. Function rest parameter

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Function rest parameter</title>
  </head>
  <body>
    <script>
      // rest parameter
      function sum(name, ...data) {
        let total = 0;
        for (const item of data) {
          total += item;
        }
        document.writeln(`<p>Total ${name} is ${total}</p>`);
      }

      sum("Orance", 10, 20, 30, 40, 50, 60);
      sum("Apple", 10, 20, 30, 40, 50, 60);
      sum("Banana", 10, 20, 30, 40, 50, 60);

      // spread syntax di rest parameter
      const values = [10, 10, 10, 10, 10];
      sum("Test", ...values);

      // arguments object
      function oldSum() {
        let total = 0;
        for (const argument of arguments) {
          total += argument;
        }
        document.writeln(`<p>Total is ${total}</p>`);
      }

      oldSum(1, 2, 3, 4, 5);
    </script>
  </body>
</html>