Function parameters are a core concept in JavaScript that allow your functions to become flexible and reusable. If you truly want to master JavaScript functions, understanding parameters is essential.
This tutorial is written in simple language and includes practical code examples to help beginners learn quickly.
What Are Function Parameters in JavaScript?
Function parameters are variables listed inside the parentheses when you define a function. They act as placeholders for the values that will be passed when the function is called.
Think of parameters as empty boxes that receive values later.
Example:
Here, name is a parameter. It will receive the value you pass while calling the function.
Parameters vs Arguments (Very Important Concept)
Many beginners get confused between parameters and arguments.
Parameters: Variables used when defining the function
Arguments: Actual values passed when calling the function
Example:
Using Multiple Parameters
You can pass more than one parameter to a function by separating them with commas.
Example:
Explanation:
aandbare parameters5and3are argumentsThe function returns their sum:
8
Default Parameters in JavaScript
Sometimes, a parameter may not receive a value. Default parameters allow you to set a fallback value.
Example:
Why This Is Useful:
It prevents errors and makes your functions more reliable.
Rest Parameters (...)
Rest parameters allow a function to accept an unlimited number of arguments.
Example:
Explanation:
...numberscollects all arguments into an arrayThis is very useful when you do not know how many values will be passed
Passing Objects as Parameters
You can also pass objects into functions to handle complex data.
Example:
This approach is commonly used in real-world applications.
Common Mistakes to Avoid
Forgetting the order of parameters
Passing fewer arguments than expected without default values
Using unclear parameter names like
a,bin real projectsConfusing parameters with arguments
Best Practices for Using Function Parameters
Use meaningful parameter names (e.g.,
userName,totalPrice)Keep the number of parameters reasonable
Use default parameters for optional values
Prefer passing objects when too many values are needed