Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Parameters และ Arguments ใน JavaScript

Parameters: ตัวแปรใน Function Definition (Placeholder)
Arguments: ค่าจริงที่ส่งเข้า Function Call (Actual Values)

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Parameters Arguments</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Function Parameters and Arguments</h1>
  <div class="sample"></div>
  <div style="color: green;" class="result"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to pass array as argument </h3>
  <script>
    let sampleEle = document.querySelector('.sample');
    let resEle = document.querySelector(".result");
    let arr = [22, 33, 44, 55];
    sampleEle.innerHTML = arr;
    function add(ARR) { // Parameter
      let sum = 0;
      ARR.forEach(el => sum += el);
      return sum;
    }
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = 'Sum = ' + add(arr); // Argument
    });
  </script>
</body>
</html>

คำอธิบาย

  • function add(ARR) → ARR คือ Parameter
  • add(arr) → arr คือ Argument
  • Default Parameters: function fn(a = 1, b = 2)
  • Rest Parameters: function fn(...args) → Array
  • arguments Object: Array-like ทุก Arguments (ไม่ใช่ Arrow Function)
  • Pass by Value (Primitive) / Pass by Reference (Object/Array)

ผลลัพธ์

Array: [22,33,44,55] | Sum = 154