Functions are mini-programs (within your big program) that you give a name to. Then you can run them again & again, just by "calling" them.
Let's make a function called shinerdog that howls
annoyingly every time we call it.
Type this into the prompt on the right: and press enter
function shinerdog() {
alert("WOOOOooooOOoOOF!")
}
Nothing happened! That's OK. All that did is tell the computer,
"hey, I'm making this function called shinerdog".
Now run the function by calling it:
shinerdog()
Damn dog is always howling at people )
Let's make another function to tell him to stop:
function shut_up_shiner() {
alert("SHINER! HUSH!")
}
Tell him what's up:
shinerdog()
shut_up_shiner()
shiner slinks away & curls up in a chair
A less annoying
alert()
alert()is just a function like any other, but it's one that comes bulit-into the web browser. We can callalert()anytime we want to display something, but that popup window is annoying.Instead -- from here on out -- we'll use its less-annoying cousin,
console.log(), which will display its results in your prompt, instead of in an annoying popup window.
That's the basics* of creating and calling a function, but so far our functions are of limited usefulness. A function that just does the same thing over & over is kind of pointless [[shrug]]
Let's do something a little more interesting. Pretend we're organizing a conference, and we want to make a computer program that will print out name bages for each of our guests.
Based on what we know so far, we could write a function that prints
Hello, my name is __________ -- but that's no good.
This is a fancy conference, so our badges need names, dammit!
Somehow, we have to tell our function the name of each guest,
so it can print out Hello, my name is Mike Jones instead.
That's where inputs come in. A function can take an input, and then use that input in its code.
This functiont akes an input called guest_name. Fill in the blank:
function print_badge(guest_name) {
console.log("Hello, my name is " + )
}
Then when you call it, you "pass" it a value for its innput:
print_badge("Mike Jones")
function shiner() {
console.log("I AM A DOG")
}