Javascript Parameters and arguments
In JavaScript, parameters and arguments refer to values passed into functions, but they serve different roles in function definition and invocation.
Parameters
Parameters are variables listed as part of a function’s definition.
They act as placeholders that allow a function to accept input when it is called.
function greet(name, age) {console.log(`Hello ${name}, you are ${age} years old.`);}
In this example,
name
andage
are parameters of thegreet
function.
Arguments
Arguments are the actual values passed to the function when it is called (invoked).
They are the data that gets passed to the function parameters.
greet("Amir", 30);
Here,
"Amir"
and30
are arguments passed to thegreet
function. They correspond to the parametersname
andage
.
Key Points
Number of Parameters and Arguments: JavaScript functions don’t enforce matching numbers of parameters and arguments. Extra arguments are ignored, while missing ones default to
undefined
.Default Parameters: JavaScript allows setting default parameter values if no argument is provided for a parameter.
function greet(name = "Guest") {console.log(`Hello ${name}`);}greet(); // Outputs: "Hello Guest"