Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tham số (Parameters) và Đối số (Arguments) trong JavaScript

Phân biệt Parameters và Arguments

Nhiều lập trình viên mới thường nhầm lẫn hai khái niệm này, nhưng chúng có ý nghĩa khác biệt rõ rệt:

  • Parameters (Tham số): Là các biến được khai báo trong định nghĩa hàm. Chúng đóng vai trò như "chỗ trống" chờ đợi giá trị.
  • Arguments (Đối số): Là các giá trị thực tế được truyền vào khi gọi hàm.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tham số và Đối số</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result, .sample { font-size: 20px; font-weight: 500; }
        .result { color: green; }
        button { padding: 8px 16px; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Tham số (Parameters) và Đối số (Arguments) trong JavaScript</h1>
    <div class="sample"></div>
    <div class="result"></div>
    <button class="btn-demo">THỰC HIỆN</button>
    <h3>Nhấn nút để truyền đối số vào hàm</h3>

    <script>
        const sampleEle = document.querySelector('.sample');
        const resEle = document.querySelector('.result');
        const arr = [22, 33, 44, 55];
        
        sampleEle.innerHTML = 'Mảng gốc: [' + arr.join(', ') + ']';

        // ARR là tham số (parameter)
        function add(ARR) {
            let sum = 0;
            ARR.forEach(element => {
                sum += element;
            });
            return sum;
        }

        document.querySelector(".btn-demo").addEventListener("click", () => {
            // arr là đối số (argument) được truyền vào
            resEle.innerHTML = 'Tổng sau cộng = ' + add(arr);
        });
    </script>
</body>
</html>

Đặc điểm quan trọng

  1. Số lượng linh hoạt: JavaScript cho phép truyền số lượng arguments khác với số parameters khai báo.
  2. arguments object: Trong hàm thông thường (không phải arrow function), có sẵn đối tượng arguments chứa tất cả arguments đã truyền.
  3. Rest parameters: Dùng ...params để gom nhiều arguments thành một mảng.
  4. Default parameters: Có thể gán giá trị mặc định cho parameters: function greet(name = 'Khách').

Ví dụ bổ sung

function demo(a, b, c = 10) {
    console.log('Parameters:', a, b, c);
    console.log('Arguments count:', arguments.length);
}

demo(1, 2);        // Arguments: 1, 2 | c lấy mặc định 10
demo(1, 2, 3, 4);  // Arguments: 1, 2, 3, 4 | c = 3, 4 bị bỏ qua (nhưng có trong arguments)