user981261
user981261

Reputation:

How do function parameters actually work?

I found a tutorial on the net and it had an example like this:

function sports(x) {
  console.log("I love " + x);
}
sports("Football");
sports("Rally");
sports("Rugby");

Why does this display the three values: Football, Rally and Rugby?

Upvotes: 1

Views: 131

Answers (4)

megazord
megazord

Reputation: 3210

I hope this helps you, x is a container for a value. So when you say something like sports ("Football"); it behaves as if this:

alert("I love " + x);

was actually this:

alert("I love " + "Football");

This is because x contains "Football".

Think of it as a placeholder for a value of some kind.

Upvotes: 1

Piotr Chabros
Piotr Chabros

Reputation: 475

Every time you write sports("text") you call a function. It means that it is executed.

Your function is displaying an alert message using an argument. In your case you execute your function three times with 3 different arguments.

Upvotes: 0

nrabinowitz
nrabinowitz

Reputation: 55678

You're defining a function, called "sports", that takes one argument, named "x". Each time you call the function, it alerts a message, substituting the argument you pass in for "x". In this example, you call the function three times, with three different values of "x".

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

Unless I'm missing something, the reason it shows all three variables (sequentially, not simultaneously) is because you're calling the function three times, each time you call it you're passing a variable ("Football" for example), which the function uses internally to complete the alerted message.

Upvotes: 1

Related Questions