Functions

JavaScript Functions are extremely useful, and they can save you from writing bunch of redundant code.

Example

One way to execute JavaScript functions is to use a button’s onclick attribute. Putting annoyingPopUp() in the onclick=”” will call the JavaScript function annoyingPopUp. Of course, that will cause the most annoying method to be called, which is alert. Alert is actually a method of the window object, but in it is often shortened to just alert(); This is a very rare exception, and most methods are not shortened like this. Whatever is inside the () of the alert() is what will be shown in an alert box.

Every time, you click this button the annoyingPopUp function will keep giving you the alert.

Example

We can see that the onclick is different in this example than the last one. The onclick=”sampleFunction(‘ Test Argument ‘)” now has a argument it is adding into the sampleFunction(). The argument ‘ Test Argument ‘ is passed into the function sampleFunction(), and the argument1 now takes the value of the ‘ Test Argument ‘. As we begin through the function, we are told to alert our new argument, argument1. The message that pops up is “Test Argument”.

Another way to call a function is to call it from another method or function:

Example

Result

777

This is similar to the last example, but the function is being called from another JavaScript method document.write(). addingFunction() is passing in two arguments this time: 333 and 444. Where 333 is being passed into the addingFunction as argument1 and 444 is also being passed in as argument2. Once they are both passed in we return the sum of the two arguments. return simply means that we will return something back to the method or function that called our function addingFunction. In the result, you can see that return sent back 777. The final statement that executed was more like document.write(777);

References

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.