Friday, 25 October 2013

JavaScript Functions

In JavaScript, you may use functions lots. A operate (also called a method) may be a self-contained piece of code that performs a specific "function". you'll recognise a operate by its format - it is a piece of descriptive text, followed by open and shut brackets.

Sometimes there'll be text in between the brackets. This text is understood as AN argument. AN argument is passed to the operate to supply it with more information that it has to method. This information may well be totally different counting on the context within which the operate is being referred to as.

Arguments may be extraordinarily handy, like permitting your users to supply data (say via a form) that's passed to a operate to method. for instance, your users may enter their name into a kind, and therefore the operate would take that name, do some process, then gift them with a personalized message that has their name.

A operate does not truly do something till it's referred to as. Once it's referred to as, it takes any arguments, then performs it's operate (whatever that will be).

Exlanation of code

Writing the function:

We started by victimisation the operate keyword. This tells the browser that a operate is on the brink of be outlined
Then we tend to gave the operate a reputation, therefore we tend to created up our own name referred to as "displayMessage". we tend to such as the name of AN argument ("firstName") that may be passed in to the present operate.
After the operate name came a curly  bracket {. This opens the operate. there's additionally a closing bracket later, to shut the operate.
In between the curly  brackets we tend to write all our code for the operate. during this case, we tend to use JavaScript's inbuilt alert() operate to pop a message for the user.


Calling the function:

We created AN hypertext mark-up language kind with AN input field and submit button
We allotted a reputation ("yourName") to the input field
We more the onclick event handler to the button. This event handler is termed once the user clicks on the button (more concerning event handlers later). this can be wherever we tend to decision our JavaScript operate from. we tend to pass it the worth from the form's input field. we are able to reference this worth by victimisation "form.yourName.value".

No comments:

Post a Comment