Functions![[next]](../../img/ltp/arrow-next.gif)
Up until now, we've been using code such as print or printp and calling these "commands." They are actually examples of a more general programming construct called functions. In this lesson, we are going to teach you how to define your own functions!
Here we create a function named "shout" that prints a string in all capitals:
|
1
2 3 4 5 6 7 function shout(text) { var upperText = text.toUpperCase() printp(upperText) } shout("Wow, functions are useful."); shout("I could do this all day."); shout("Now my throat hurts."); |
Click to run the code. |
Exercise: Shout in bold. Change the above program to use the HTML bold tag (<b>) to shout even "louder."
Any kind of code that you are already familiar with can go inside a function, but it will only run when the function is called. The following example uses a for-loop inside a function.
Here we define a new function called "multiprint" that uses a for-loop inside it.
|
1
2 3 4 5 6 7 function multiprint(count, message) { for (var i = 0; i < count; i++) { printp(message) } } multiprint(10, "I will not throw " + "paper airplanes in class.") |
Click to run the code. |
Line 1 in the is called the function "signature". It indicates how many "arguments" the function has and what to name those arguments. Those names are available for use within the function.
Exercise: Multiprinting user input. Write a program that uses the form function we learned about earlier to ask the user for a message and the number of times to repeat it, and then calls multiprint with the appropriate arguments. (See this app for the solution if you are stuck).
function.In the function defined above, any code in the body that refers to either count or message will see the arguments the function is called with.
forEachSome functions even take functions as arguments. A feature unique to JavaScript and a few other high-level languages is the ability to store functions in variables and pass them around. For example, arrays have a forEach method whose single argument is itself a function. This lets us do something to each element in an array without having to write a loop.
|
1
2 3 4 5 6 7 8 9 var bands = [ "Fall Out Boy", "Usher", "Linkin Park", "Ne-yo", "Alicia Keys" ] function critiqueBand(band) { printp(html("<i>"+band+"</i> kinda sucks.")) } bands.forEach(critiqueBand) |
Click to run the code. |
This example passes a function (critiqueBand) as an argument to another function (bands.forEach).