JavaScript

JavaScript Function Parameters and Arguments


JavaScript functions can accept parameters (also known as formal parameters) to receive input values when they are called. These input values are called arguments. In this guide, we'll explore how to work with function parameters and arguments and provide examples to illustrate each concept.

Defining Functions with Parameters

You can define a function with parameters by specifying them within the function's parentheses:

function greet(name) {
    console.log(`Hello, ` + name + `!`);
}
function add(a, b) {
    return a + b;
}
    

Passing Arguments to Functions

When you call a function, you pass arguments as values to the corresponding parameters:

greet(`Alice`); // `Alice` is the argument for the `name` parameter
const result = add(5, 3); // 5 and 3 are the arguments for the `a` and `b` parameters
    

Default Parameters

You can provide default values for function parameters, which are used when the arguments are not provided:

function greetDefault(name = `Guest`) {
    console.log(`Hello, ` + name + `!`);
}
greetDefault(); // Uses the default `Guest`
greetDefault(`Bob`); // Uses the provided `Bob`
    

Rest Parameters

Rest parameters allow a function to accept a variable number of arguments as an array:

function sum(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}
const result = sum(1, 2, 3, 4, 5); // Accepts any number of arguments
    

Arguments Object (Legacy)

In legacy JavaScript, you can use the arguments object to access all arguments passed to a function, even if they are not explicitly defined as parameters:

function legacyFunction() {
    for (let i = 0; i < arguments.length; i++) {
        console.log(`Argument ` + i + `: ` + arguments[i]);
    }
}
legacyFunction(1, `apple`, true); // Outputs all arguments
    

Conclusion

Understanding function parameters and arguments is essential for building flexible and reusable functions in JavaScript. Whether you're defining functions with parameters, using default values, or working with rest parameters, these concepts empower you to create versatile functions for various use cases.

Happy coding!

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.