Javascript functions, how can I start beginning to understand them?
Functions in programming are similar to functions in math. They take some input and produce an output (well, sometimes they don't, but they do something). They are great to organize your code, encapsulate functionality and to avoid writing the same code at different places (DRY).
Functions taking more parameters are not necessarily more complex.
Have a look at
- Wikipedia - Function(programming)
- MDC - JavaScript Guide
- especially MDC - JavaScript Guide: Functions
- MDC - JavaScript Reference: Functions and function scope
Functions provide a way to segment repeated portions of your code so that you don't have to write the same functionality over and over again.
If you're after a non-programming analogy, you can think about it in business terms:
Imagine you have to print, collate, hole-punch and bind a document. First time around, you do it yourself. Then next time, you have to do it yourself again... and again... So, what can you do? You can hire an admin assistant (let's call him Bill) to do that for you. Then, the next time you have to print, collate, hole-punch and bind a document, you can just tell Bill which document to print (a single parameter) and he'll do it for you and bring the document back to you when it's finished.
In this case, Bill's a function that does some work and returns something (or, at least, an example of one!)
Now, imagine you want to send a letter to someone to chase a payment. Of course, you could type the letter and post it yourself, but wouldn't it be easier if someone else did it for you? Let's call her Jane. You can tell Jane which company to send the letter to and how much they owe (the parameters) and she'll go off, type it and send it. You don't necessarily need to know whether she's done it or not, because you trust her to get the job done.
In this case, Jane's a function that doesn't return anything but still does some work.
There are two things you must understand, in my opinion:
- the DOM structure, which is actually what you manipulate using JavaScript
- the JavaScript language (or even programming altogether)
I'd go for a basic tutorial like this one: http://www.lynda.com/JavaScript-tutorials/Essential-Training-2011/81266-2.html
And the most important part is not just reading, doing a lot of examples and exercises. If you don't code, you can't get the hang of it.