Skip to content

Instantly share code, notes, and snippets.

@aspencer8111
Last active October 27, 2018 19:43
Show Gist options
  • Save aspencer8111/3efa8cdf2e169ffa41f9240cc12d4fb8 to your computer and use it in GitHub Desktop.
Save aspencer8111/3efa8cdf2e169ffa41f9240cc12d4fb8 to your computer and use it in GitHub Desktop.
Javascript functions explained

Learn your JS functions and arguments

A function has a few parts:

  1. The declaration: function ...
  2. The name: function foo...
  3. The arguments: function foo(arguments go here!)...
  4. 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.

What are arguments good for?

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.

Arguments to the rescue!

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 Alex
  • sayHi('you') // prints Hello you
  • sayHi('Keri') // prints Hello Keri
  • sayHi('whatever') // prints Hello whatever
  • sayHi(5) // prints Hello 5

SO MUCH MORE FLEXIBLE!!! NICE! :)

Wait...Why didn't we ever run the functions (i.e. foo()) in the primer exercises?

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?

HOMEWORK! - Do in a JS bin and email the link to your mentor

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment