The difference between parameters and arguments in Javascript is one that puzzles many beginners, myself included. It's an important concept that might take a bit of time to grasp; there have been more than a few times that I've been writing functions or reading others' code and I've asked myself where the parameter was defined, only to remember that a parameter doesn't need defining.
Let's break it down....
A parameter is the name given to an element at its time of declaration.
It doesn't need defining. A parameter is a stand-in value that represents what will be there once the function is called. It could be anything, but it's typically best to name it something that's representative of what will be there eventually. It's defined inside parentheses () next to the function they're used for (this is the function declaration).
Then there's arguments:
An argument is the actual value supplied to the parameter (what will be there eventually). This occurs when the function is called (or invoked) -- AKA when the function is used later in your code.
So, a parameter is sort of a poser, while the argument is the real deal.
Here's an example:
In this code, the word 'data' represents the parameter. Let's see it in use:
The word 'argument' is what is passed in for the parameter when the function is called. When you are writing the code itself, the parameter isn't defined; it's a placeholder for the argument. This allows the function (in this case, learningParameters) to be used again and again, with different arguments.
But what if there are two parameters, or you're given a deliverable that requires two arguments?
When you have a function with two parameters, it means that the function expects to receive two arguments when it's called. Here's a visual:
Let's do an example with numbers instead of words:
It's the same!
Typically, if you want three arguments, you would provide three parameters. However, this isn't always the case; sometimes there's only one parameter, but three arguments will be passed. It's important to adopt a level of flexibility when writing with JavaScript.
It took me a while to wrap my head around this. It seems like such a basic concept, but I sometimes still need reminding -- just yesterday I caught myself looking for a parameter's definition in my own code, and then remembered it's just a placeholder for the data to come! Once you've caught on, you'll be able to continue tackling more and more difficult concepts.
You've got this!
Top comments (0)