A function has a few parts:
- The declaration:
function ...
- The name:
function foo...
- The arguments:
function foo(arguments go here!)...
- The code to be executed: (inside the { } brackets):
function foo() {
code to be executed goes here
}
NOTE Functions don't get ran until they are called. They just stay in memory and wait to be called.
So this doesn't do anything:
function foo() {
console.log('I was just ran!');
}
until someone calls it by doing this: foo()
// prints 'I was just ran!' to the console.
They make functions more flexible! Consider this:
function sayHi(){
console.log('Hello world!');
}
This function can print out "Hello world!" as many times as we are willing to call it.
So sayHi()
. So calling sayHi()
, sayHi()
, sayHi()
, sayHi()
, sayHi()
will print 'Hello World!' 5 times over. But that sucks! It can only greet 'world'. I want it
to greet me, then you, then my wife Keri, then anyone else I deem worthy.
I'm going to use name as the argument, but I could have called it anything its just me choosing a label that I can then call to in the console.log code.
function sayHi(name) {
console.log('Hello ' + name);
}
sayHi('Alex')
// prints Hello AlexsayHi('you')
// prints Hello yousayHi('Keri')
// prints Hello KerisayHi('whatever')
// prints Hello whateversayHi(5)
// prints Hello 5
SO MUCH MORE FLEXIBLE!!! NICE! :)
Because that is what the automated tests are doing!
They run the function sayHi()
. Pass in different arguments sayHi('Keri')
,
and make sure the functions we write return the correct values Hello Keri
.
This is how code is tested in real life! In fact, the automated test that checks our sayHi function might read something like:
expect(sayHi('Bob')).to return('Hello Bob')
See how that works?
Write a function that takes in a name argument and greets that name in a console.log (just like we did above).
Call it with a bunch of different names.
Write a function that takes in one argument - an array
have that funciton console.log (print) any number in that array
that is an even number (hint: even numbers have no remainders when divided by 2)
Call that function and pass in [1, 2, 5, 6, 8, 12]...what prints out?
Call that funciton and pass in [10, 1, 4, 20, 19]...what prints out?