Working with the arguments Object in JavaScript


Use the built-in arguments object to access all the parameters of a function inside a function.

The arguments object is an array-like object. You can access its values using an index similar to an array. However, it does not support array methods.

Example: Arguments Object
function displayMessage(firstName, lastName) {
    alert("Hello " + arguments[0] + " " + arguments[1]);
}

displayMessage("Steve", "Jobs"); 
displayMessage("Bill", "Gates");
displayMessage(100, 200);

The arguments object is still valid even if a function does not include any parameters.

Example: arguments Object
function displayMessage() {
    alert("Hello " + arguments[0] + " " + arguments[1]);
}

displayMessage("Steve", "Jobs"); // display Hello Steve Jobs

An arguments object can be iterated using the for loop.

Example: Access all Parameters
function displayMessage() {

    for(var i = 0; i < arguments.length; i++){
        alert(arguments[i]);
    }
}

displayMessage("Steve", "Jobs"); 

It is recommended to use rest parameters instead of the arguments object because the rest parameters provide a cleaner syntax and are easier to work with.