How do you handle a function that takes in a variable or a number of variables as parameter?

In some of the lessons, I noticed that functions are declared, which take in parameters. However, the confusion is that these parameters “as” variables are never declared anywhere.

How do these variables work as parameters when they are fed values as arguments since they are not declared before or within the functions?

The point of the parameter is to be used to define the variable on a case-by-case basis, for each function call, greatly improving the adaptability of your function.

Let’s take function saySomething(text) as an example. text is a parameter. In the body of our function, we can write console.log(text); and it’ll work just fine, because the value of the variable has been defined… in the function call.

When we call the function, we write saySomething("Hello, World!");

In this line, we are defining the value of the text for the duration of the saySomething() function call as String "Hello, World".

So where is it declared?: In the function declaration, as a parameter (argument). Where is it assigned?: In the function call, to the already declared parameter.


Additional Resources:

3 Likes

In short…

parameters  =>  variables
arguments   =>  objects

Within the context of the function, the object sent as the argument will be known locally by the name of the parameter.

function add(a, b) {
    return a + b
}

Above, the function takes two arguments, known as positional arguments because their position matters.

console.log(add(6, 7))    //  13

Above we log the return value of the function add() when given 6 and 7 as arguments. 6 will be the value referenced by a since their positions match. 7 will be the value referenced by b. Note the variable -> object connection.

1 Like

Awesome clarification!

So in essence, the parameters are like “declared variables.”

Then the arguments you pass in when you call the function are like “assigned values” to the “declared variables.” Is this correct?

Also, does it mean, when you declare a function, like so

function checkStuff(name){
}

Then there’s no need to declare the variable “name” again within the function block, like so

function checkStuff(name){
let name = "something";
}

?

Since your “name” parameter is serving as a “declared variable” which will be assigned a value much later as argument when the function is called and a value passed in.

That would be going against everything we have learned.

Now I see :smile:

Thanks.

1 Like