Reputation: 31
Firstly, I'm a beginner, so don't be mad if what I'm saying is stupid.
So, this is the code that is using parameters:
function simpleExample (x) {
document.write ("I love " + x);
}
simpleExample ("my mom.");
And this is the code that doesn't use the parameters:
function simpleExample () {
var x = ("my mom");// Does not use the parameters
document.write ("I love " + x);
}
simpleExample ();
So, the result is the same and... the global and local thing is also the same [both is local right?] So what does the difference?
Sorry if it's a dumb question.
Upvotes: 2
Views: 293
Reputation: 385
Using parameters is the essence of functions.
In the second case, the variable x is local to the scope of the fonction and will never change. That is, the execution of your function simpleExample
will always have the same effect (logging "I love my mom" in the console).
The use of parameters allows your function to have an effect dependent to the input. In this case, the person you love can be changed depending of the parameter x
.
Upvotes: 0
Reputation: 8334
Using a parameter for a function allows the result of the function (be it a process or a result value) to differ based on an input that is not fixed at the time of writing the function.
Even with your simple example it should be obvious that the simpleExample(x)
function with a parameter can be easily reused like so:
simpleExample('my mom');
simpleExample('and my dad too!');
simpleExample('my sister not so much');
This wouldn't be as easy with the variable approach.
Upvotes: 0
Reputation: 334
You maybe right if you just want to say you're loving your mom. But, what if you also want to say other persons that you love? You write all that hard code everytime?
the answer is : no.
You just call that function with a parameter. And that's it. Nothing more.
simpleExample("my mom");
simpleExample("my dad");
simpleExample("justin bieber"); //we all hope you don't.
Upvotes: 3
Reputation: 665584
Why use the parameters if we can use variables?
The point is that often we cannot use static (global) or constant variables. Consider your first function:
simpleExample("my mom.");
simpleExample("my dad.");
We are calling the same function multiple times with different arguments. This requires parametrisation of the code in the function that is otherwise the same for all cases.
Upvotes: 0