Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

When to use parameters in a custom function  RSS feed

 
Robin Mantley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

If this has been already asked, please feel free to post the link. If not, here is my problem:

While I can understand simple examples of passing parameters to functions, i.e.:

I'm having trouble applying it when the function is more complex, i.e.: contains several parameters representing different "types" of arguments values.

When I have to write a custom function (or read someone else's):
a) How would I know I need to pass parameters to the function?
b) How would I know what the other persons' parameters represent?
c) Is passing parameters the same as defining variables within the function (using "var")?

HTML:
Example 1:

Example 2:

Example 3:


Example 4:
I thought I was understanding the basics of javascript and have done much reading and online tutorials. Trouble is, the examples of functions that pass parameters already provides the parameters needed, so I don't really have to think about whether or not they are needed -- but I want to understand! Please help me. I've taken tests and quizzes and done very well. I don't say that to brag, but with humility of a student seriously seeking to understand javascript. For some reason, book are not enough. With all due respect, I don't want to just pass tests or only write snippets of code using jQuery.

Please, I'm not asking anyone to just hand me the code, but if code is given, help me to understand if I should use parameters, and the proper scenario to use them or not. My examples above are things I've been testing to see if I understand how to use parameters, but I am hitting a brick wall...

I use the jQuery api (which uses selector/element parameters passed to the jquery function to create a jquery object). But if I create a custom function, I don't pass any parameters to the function, unless I'm using the jquery api and need to pass the selectors.

Thanks, I am grateful for your help. If my examples are hard to understand, I apologize. I know this post is long, but it is the first one, and hopefully going forward I will be more succinct now that you have some history of my quandary.

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66257
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!
Robin Mantley wrote:When I have to write a custom function (or read someone else's):
a) How would I know I need to pass parameters to the function?

If the function needs information, that information is generally passed as parameters. Do not fall into the trap of implicitly using global variables. (Closures are a topic for later, but keep in mind for the future that scope in JavaScript is a complex topic.)

b) How would I know what the other persons' parameters represent?

Documentation. Failing that, read the code.

c) Is passing parameters the same as defining variables within the function (using "var")?

Mostly. The scope of the parameters is limited to the scope of the function. It's not a bad idea to think of them as local variables that are in scope for the duration of the function lifetime. (Again, this is more complex than just when the function is "running", but it will do for now.)

I didn't look at your examples closely due to the lack of proper indentation. Please be sure code is properly formatted when posting. Kudos for using code tags, though!

But most of your confusion stems from the fact that you think the alert() function accepts more than one parameter. It doesn't. Also, using alert() as a debugging tool is pretty poor. I'm not sure why you are focusing on it.

Beyond that, I'm not really sure where your confusion lies. Your examples aren't serving to help understand your confusion because they rely upon a false assumption (that alert() is a good way to test things, and accepts multiple parameters).

If you must use logging, use console.log() and make sure that the JavaScript console is open.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66257
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why would you want to redefine a parameter name with a local variable?
 
Robin Mantley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Bear for the friendly welcome and your detailed reply. I liked the tagline about greenhorns. I bought one of your books last year! Secrets of the Javascript Ninja! Is there a section in that book where you discuss function parameters? I didn't finish reading it.

I didn't look at your examples closely due to the lack of proper indentation. Please be sure code is properly formatted when posting. Kudos for using code tags, though!


I indented the code and updated comments, I'm sorry I missed that. I read the terms and conditions when I joined, and all it stated was "be nice". I didn't go any further to find other documentation on how to format the code in the posts, but I should have known better.

I don't understand why, however in example 1 and 2, the first argument is not returning any value. And in example 4, I'm getting an error even though I'm declaring and assigning the variable as I did in the other examples. Example 3 is logging all args correctly. Could you help me understand this?

But most of your confusion stems from the fact that you think the alert() function accepts more than one parameter. It doesn't. ."


I changed the code from using the alert() to console.log() function. I didn't realize alert() only takes one argument. I followed the link you posted, but I must be missing that information on the page.

Also, using alert() as a debugging tool is pretty poor. I'm not sure why you are focusing on it"


I was using the alert() function to follow the example in a sitepoint book I am using. Also, I must have mixed up this book with another book I was reading where the author wrote: "Why did I use alert in examples ... it works reliably in every browser... not necessarily ideal...". The author probably didn't pass more than one argument to the alert() function though, so I was wrong to use alert() instead of console.log(). I usually use the console.

Documentation. Failing that, read the code.


As far as the other person's parameters, I ran into a situation where the code was not well written, nor was there any documentation. I tried using Chrome Dev tools to debug to find the values of the parameters, but was unable to. This is another reason I am asking about understanding parameters.

If the function needs information, that information is generally passed as parameters"


Would you please explain to me in more detail what kind of information the function needs and does it have to be as parameters in parentheses? I think this is where I am getting stuck.

Why would you want to redefine a parameter name with a local variable?


That is one of my questions. Are the local variables the parameters? If so, I was assigning a value to parameter (or local variable) to pass to the function. Wait a minute, so I don't pass the parameter to the function?

Your examples aren't serving to help understand your confusion because they rely upon a false assumption (that alert() is a good way to test things, and accepts multiple parameters).

My examples are so rudimentary, but at this stage of my learning, I did that on purpose to understand what I'm doing and why (baby steps). I made the variables local to the function using the parameter names. This again is my confusion and why I am posting this question. I don't know why it is so hard for me to understand this concept of parameters. I really need help...

Thanks again.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66257
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Robin Mantley wrote:I bought one of your books last year! Secrets of the Javascript Ninja! Is there a section in that book where you discuss function parameters?

Chapters 3 and 4 examine functions and function calling in detail.

I didn't go any further to find other documentation on how to format the code in the posts

See the link in my sig on asking questions. Hope that helps.

I don't understand why, however in example 1 and 2, the first argument is not returning any value.

Have you checked what's in the variable using the console? It's highly likely your are getting no value back from the jQuery call.

But I'm still not sure what your examples are trying to accomplish. If you are just trying to figure out how parameters are working, why are you using jQuery calls to set the values of local variables?

After you see my example below, it might be best to post again (please don't go back and re-edit older posts), with an example and what you want to learn from it. It's not clear to me from your first post exactly what you expect each example to show.

I followed the link you posted, but I must be missing that information on the page.

The page clearly shows that the syntax for the method is:

window.alert(message);

One parameter: message

I was reading where the author wrote: "Why did I use alert in examples ...

Either the book is very old, or, well, I disagree with the author. alerts are an awful way to to do just about anything. Every modern browser has powerful debugging tools built right in; including the console. These are the tools you should use.

As far as the other person's parameters, I ran into a situation where the code was not well written, nor was there any documentation.

Unfortunately, this is all too common and you'll run across it often.

I tried using Chrome Dev tools to debug to find the values of the parameters, but was unable to. This is another reason I am asking about understanding parameters.

Set a breakpoint inside the function. When stopped at the breakpoint, the parameters will be part of the scope, just like local variables. You also have direct access to the list of arguments via the implicit arguments parameter.

Would you please explain to me in more detail what kind of information the function needs and does it have to be as parameters in parentheses? I think this is where I am getting stuck.

That, of course, greatly depends upon the function. But I'll try an example. Let's say we were writing a function to display a Google map on the page. In order to create the map and initialize it properly there are any number of values we might need; for example: the latitude and longitude of the map center, the zoom level, whether to include satellite view, and so on. If we don't define the function to take these values as parameters, how could we write the function without using hard-coded values?

Why would you want to redefine a parameter name with a local variable?


That is one of my questions. Are the local variables the parameters?

You would never see real-world code that does this. Keep reading...

If so, I was assigning a value to parameter (or local variable) to pass to the function. Wait a minute, so I don't pass the parameter to the function?

I am not sure what you are asking here. When a parameter is defined for a function, it is available within the function by name. Creating a local variable with the same name will just mask the parameter, so why do that?

I don't know why it is so hard for me to understand this concept of parameters.

You may simply be over-thinking things. I'll repeat what I said above
Bear wrote: When a parameter is defined for a function, it is available within the function by name.
For example:

Notice how we can use the parameters within the function by name. No need to create local variables, no need to do anything special. You can think of the parameters as local variables that are automatically created for you and available within the function. We don't have to do anything more than list them in the function signature.

Example to call the above:

makeMap(40.4, -97.1, 8);

Does that help?
 
Robin Mantley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Bear. Yes, your last example and the explanations to my comments and questions you have given are very helpful. After reading your posts a few times and going back and forth on my examples, I am beginning to see what I have been mixing up. Please let me know if I am understanding this correctly:

Parameters are passed to a function when I don't know what their values will be -- but the arguments passed to the function when it is called are the values of those parameters. The arguments (values) also must be passed in the same order as the parameters (right?) and the parameters should be named in such a way that describes what information the value (argument) represents.

Variables are listed in the function (not using the same names as the parameters) when I want to assign a value to them in the function.

I'm hoping I will never see a real-world example of assigning a value to parameter (or local variable) to pass to the function. But would this represent a real-world example (this is just snippet showing parameters with values -- I did not write this code but had to debug it to find out why showSiblings was not working) To me, it looks like a config object is being created with properties that are the parameters and those parameters are assigned values. Is this a good example?


I didn't post this code initially because I don't want to give the impression that I just want someone to give me the answer, so I was trying to give examples of how I was interpreting the code. I really want to know how to find the answer so that I can use that kind of knowledge in other situations. This is a real learning process for me and I want to understand more than anything.

Thanks again very much for your help!
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66257
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Robin Mantley wrote:Please let me know if I am understanding this correctly:

Parameters are passed to a function when I don't know what their values will be -- but the arguments passed to the function when it is called are the values of those parameters.

Yes.
The arguments (values) also must be passed in the same order as the parameters (right?)

Yes.
and the parameters should be named in such a way that describes what information the value (argument) represents.

Yeah, but I'd word it more along the lines of: the parameters should be named in such a way that describes how they are used by the defining function.

Variables are listed in the function (not using the same names as the parameters) when I want to assign a value to them in the function.

Variables are created inside a function a they are needed to hold some data. Not all functions will have variables, and the variables have nothing at all to do with the parameters.

I did not write this code but had to debug it

That is somewhat advanced code for a novice, so it's easy to see why it could cause some confusion.

To me, it looks like a config object is being created with properties that are the parameters

No. Look at the code before the config object creation. What do the parameters passed to the function opened on line 5 have to do with the config object? Absolutely nothing. Again, do not try to conflate things that are distinct. The config object is simply created with an object literal that has properties with various names like showSiblings and match. None of that code up to point has anything at all to do with parameters. Why do you think that it does? Stop thinking that there's some magic. There isn't any. (At least not in this code). The parameters that are in scope as of lines 8 through 14 in which the config object is created are: $, w, _ and g (I won't get into those choices right now).

What do those parameters have to do with the config object? Nothing. So when looking at the config object, you shouldn't be thinking about parameters at all. There's nothing there to indicate anything at all to do with parameters.

Now following that code, there is a function declared that has parameters that use the same names as properties in the config object. Why? I don't know. This is obviously not a complete code segment so I have no ides how this function may be used in the future. But the fact that a completely unrelated function to the config object uses names that are the same has no significance to the config object itself.

Do you understand what the code on lines 20 through 24 is doing?

 
Rob Crowther
author
Ranch Hand
Posts: 297
5
Android Fedora Firefox Browser
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MDV.mainNav is a function with six named arguments. By the look of it those are being sanity checked and given default values, though I think this is actually unnecessary, more on that later.

If you call a function without specifying all the arguments then the remaining arguments will have a type undefined, that's what all those if (typeof lines do. So if you call:

Then all of those arguments will have type undefined within the function. If, on the other hand, you call:

Then ulTagId, parentUrl, showSiblings and showChildren will all have a type (ie will not be of type undefined), but showFourthLevel and pageTitleTagId will still be of type undefined.

Depending on whether the argument parentUrl has been passed MDV.gNav.Generator.init function is called either with no arguments or being passed a single parameter. The parameter being passed in the latter case is an object (that's what the squiggly brackets are - an object is being created inline to pass to the function).

The second case is why I said earlier that giving the default values was unnecessary. The 'pass an object' in pattern is fairly common in JavaScript, the function has a set of defaults defined as an object then the argument is merged into that default. This approach has the advantage that you can add your parameters to the object in any order and, if you want to accept the default, you just don't add that property as opposed to calling a function with multiple arguments where it is awkward to pass the (say) only the first, third and fifth arguments. So, assuming the init function follows this patter, what I'd actually expect the mainNav function to look like is:

However, that is by the way, and you've not posted the definition for init so I can't be sure. As far as your problem is concerned I would guess that showSiblings is not working because that value is not getting passed into MDV.gNav.Generator.init as part of that single object parameter. Probably what you need is:
 
Robin Mantley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Bear. Again you are making things much more clear to me and appreciate your time and patience! The function that contains this code is extremely long (over 500 lines) and I didn't want to post it all. Here is more detail:



But yes, you are right, there are several functions within the function (which starts on line 5) where the config object is created (and in one of those inner functions, config.showChildren or config.parentUrl are being used), and because of this, I began to get confused with parameters and variables because they are share the same name...
What do those parameters have to do with the config object? Nothing. So when looking at the config object, you shouldn't be thinking about parameters at all. There's nothing there to indicate anything at all to do with parameters.

Here is where I began to think of the parameters in the config object as arguments to a function:

Now following that code, there is a function declared that has parameters that use the same names as properties in the config object. Why? I don't know. This is obviously not a complete code segment so I have no ides how this function may be used in the future. But the fact that a completely unrelated function to the config object uses names that are the same has no significance to the config object itself.

Here is how the function is being used in the future. The following function is being called within the HTML -- the arguments past to this function:


I thought I did and here, again, is why in my initial examples above, I was assigning values to the parameters.

In lines 20 - 24, are these the default values for the parameters and the properties in the config object?

Can you now see the beginning of my confusion about variables and parameters? Since those "elements" are named the same, it appears to me that in one case, they are being passed to a function as parameters, in another case, they are being given a value within that function, and in another case, are being passed as arguments when the function is called.

Bear, based on your advice to me, I know now that I am interpreting this all wrong (and again thanks for helping me), but can you see how this code can be misinterpreted by someone still learning?

From my usage of jQuery and/or javascript, I have an understanding of how to pass arguments when the function is called, but what I don't quite understand is how to create a function properly that will need to use parameters in the first place. Some functions don't have any parameters passed to it, for example the getDateOpened method:


That is a simple example, yes, but could this have been written by passing a parameter?

Thank you for your continued help. I promise I am not trying to confuse anyone.
 
Robin Mantley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second case is why I said earlier that giving the default values was unnecessary. The 'pass an object' in pattern is fairly common in JavaScript, the function has a set of defaults defined as an object then the argument is merged into that default. This approach has the advantage that you can add your parameters to the object in any order and, if you want to accept the default, you just don't add that property as opposed to calling a function with multiple arguments where it is awkward to pass the (say) only the first, third and fifth arguments.

Thanks, Rob. I do understand what you have written and I appreciate how you explained why the 'config' object was created and how this type of object can be used as arguments in the function.
As far as your problem is concerned I would guess that showSiblings is not working because that value is not getting passed into MDV.gNav.Generator.init as part of that single object parameter.

Yes, I would think that would work, but there is nothing in the code that defines what would happen if the showSiblings parameter/argument is false. So since its default is true, its unnecessary to add it in the function call as you said above. The fact that that conditional code is missing from the entire function is what was confusing me, along with this being advanced code (for me).

Thanks again!
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66257
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Robin Mantley wrote:
In lines 20 - 24, are these the default values for the parameters and the properties in the config object?

Yes, this code is applying defaults to the parameters. But no, it has nothing to do with the config object. The names being used are those of the parameters. The fact that some other object (config) has properties with the same name has no bearing on this code. At all.

Look at those lines again. Do you see the keyword var anywhere? No. No variables. Just parameters.

Here is where I began to think of the parameters in the config object as arguments to a function:

Don't. and the config object does no have parameters; functions have parameters. Objects do not (ignore that a function is a type of object for now). Objects have properties, not parameters.

Can you now see the beginning of my confusion about variables and parameters? Since those "elements" are named the same, it appears to me that in one case, they are being passed to a function as parameters, in another case, they are being given a value within that function, and in another case, are being passed as arguments when the function is called.

It's all about scope. The same names used elsewhere don't always mean the same thing.

From my usage of jQuery and/or javascript, I have an understanding of how to pass arguments when the function is called, but what I don't quite understand is how to create a function properly that will need to use parameters in the first place.

Comes with practice. Again: you will define parameters for a function, when it needs information from the caller that is not already provided by the scope of the function (e.g. gloabls and closures -- bit that's what chapter 5 in Ninja is all about).

Some functions don't have any parameters passed to it, for example the getDateOpened method:

Right, that's likely a getter that simply returns a value that it already knows about. it does;t need any info from the caller of the function to do its job.

That is a simple example, yes, but could this have been written by passing a parameter?

Not if the function does;t expect one. (Caveat: you could pass an argument to the function, but if the function never references it, it's moot.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!