JavaScript Function Parameters
Subject: JavaScript
Function parameters in JavaScript allow you to pass values into a function so it can perform tasks using those values. Parameters are defined in the function signature, and values passed to them are called arguments.
What Are Parameters?
Parameters are variables listed inside the parentheses in a function definition.
Here, name is the parameter.
Passing Arguments to Functions
Arguments are actual values passed to a function when it is called.
Multiple Parameters
You can define more than one parameter separated by commas.
Default Parameters
Default parameters assign a fallback value when no argument is provided.
Rest Parameters (...)
Use rest parameters to accept a variable number of arguments as an array.
Arguments Object (Pre-ES6)
Prior to ES6, the arguments object was used to access all passed arguments.
Note: arguments is not available in arrow functions.
Destructuring Parameters
You can destructure arrays or objects directly in the parameter list.
Key Takeaways
- Parameters are declared in the function; arguments are values passed when calling it.
- Use default parameters to provide fallback values.
- Use rest parameters (
...) to gather extra arguments into an array. - Prefer rest parameters over the legacy
argumentsobject. - Destructuring helps simplify object or array arguments for cleaner code.