Functions
Remember that a variable is a name for a piece of data
A function is the name for a piece of code
Why would you want to name a chunk of code?
Perhaps...
 you have some code you want to run again and again
 you want to do the same operation on different values
 you want to keep your code organized
Function example
Here's an example function:
function add(x, y) {
let sum = x + y;
return sum;
}

function
means "define a function" 
add
is the name of the function 
x, y
are the parameters of the function (also called arguments) 
sum
is a local variable of the function 
sum
is also the function's return value because of the magic word return
Calling a Function by Name
You call a function by its name, plus parentheses:
function add(x, y) {
let sum = x + y;
return sum;
}
add(2, 3) // returns 5
add(12, 30) // returns 42
Lab: One Nation, Divisible
One number is divisible by another if you divide them and the remainder is 0.
Write a function called divisible
that takes two numbers, and returns true
if the first number is divisible by the second number, and false
otherwise.
divisible(100, 10) //=> true
divisible(100, 7) //=> false
divisible(3333, 11) //=> true
divisible(99, 12) //=> false
Divisible solution
Hint 1
Hint 2
if(/*this expression evaluates true*/) {
//do this
} else {
//otherwise do this
}
Solution
function divisible(operator, operand) {
if(operator % operand) {
return true
} else {
return false
}
}
divisible(100, 10) // => true
Shouter
Here is a function that takes some String as input, and as output returns a shouted version of that String.
function shouter(someString) {
let loudString = someString.toUpperCase();
return loudString + '!!!';
}
shouter('i like pizza'); => 'I LIKE PIZZA!!!'
The variable loudString
is called a local variable and can only be used inside the function.
Lab: Capitalize
Please write a function that returns a Capitalized version of a word. Only uppercase the first letter of the word.
For example:
capitalize('tomato')
returns 'Tomato'
A solution is on the next slide, but try to solve it on your own. Remember that there are many string operations available to you...
Capitalize Lab Solution
Hint One
let firstLetter = string[0]
Hint Two
let restOfString = string.slice(1)
Answer
function capitalize(word) {
let firstLetter = word[0];
let restOfWord = word.slice(1);
return firstLetter.toUpperCase() + restOfWord.toLowerCase();
}
console.log(capitalize('smith'));
console.log(capitalize('MACGUYVER'));
Passing Variables to Functions
When you pass a variable to a function, that variable's value is assigned to a parameter.
The variable and parameter names do not need to match!
function shouter(someString) {
let loudString = someString.toUpperCase();
return loudString + '!!!';
}
let feeling = "I feel great";
let strongFeeling = shouter(feeling);
Outside the function  Inside the function  Value 

feeling 
someString 
"I feel great" 
loudString 
"I FEEL GREAT" 

strongFeeling 
"I FEEL GREAT!!!" 
Four Function Syntaxes
WARNING: JavaScript has many ways to define a function.
function add(x,y) { return x + y; }
The following are all roughly equivalent to the above:
let add = function(x,y) { return x + y; };
let add = (x,y) => { return x + y; };
Arrow Function Expression with implicit return value
let add = (x,y) => x + y;
 Note that these new forms are anonymous, meaning there is no name between
function
and(x,y)
 the name of the function is the name of the variable that points to it
Lab: Age Calculator
Write a function that calculates the number of seconds old you are when given your age
let age = 27
function ageCalc (num) {
//Your code goes here
}
ageCalc(age) // should print "You are 852055200 seconds old." to the console
How could we use ARGV to make this more modular?
Flip it around!
Can you write the inverse function; one that takes a number of seconds and tells you the exact age?
You can get the current date by calling Date.now()
which will give you a time in milliseconds, and the date you were born by creating a new Date
object. You can then figure out the time that's elapsed in milliseconds by subtracting the date you were born from the current date
let date = new Date(1992, 05, 12, 3, 14) //new Date(year, month, day, hour, minute)
let ageInMilliSec = Date.now()  date
Solution
Here's one solution for the age calculator:
Answer
let age = 27
function ageCalc(num) {
let secondsInMin = 60
let minInHour = 60
let hrInDay = 24
let dayInYr = 365.25
let secInYr = secondsInMin * minInHour * hrInDay * dayInYr
let ageInSec = num * secInYr
return ageInSec
}
console.log(ageCalc(age))
Lab: Supply Calculator
Write a function that:
 accepts three arguments, a starting age, an amount per day, and an item name
 calculates the amount of items used over the course of the rest of your life
 based on a 100 year constant max age
 Outputs "You will need Number Items to last the rest of your life." e.g.
supplyCal(20, 3, "cookie") // => "You will need 87600 cookies to last the rest of your life"
supplyCal(99, 3, "cookie") // => "You will need 1095 cookies to last the rest of your life"
supplyCal(0, 3, "cookie") // => "You will need 109500 cookies to last the rest of your life"
Supply Calculator inspired by the Lifetime Supply Calculator lab designed for the Girl Develope It! curriculum. The original can be found here
Supply Calculator Solution
Hint 1
Calculate the number of cookies needed per year
let amountPerYear = amountPerDay * 365
Hint 2
Calculate the number of years of life left
let numberOfYears = 100  age
Solution
Use the number of cookies per year, and number of years of life, to calculate the total cookies
function supplyCalc(age, amountPerDay, item) {
let amountPerYear = amountPerDay * 365
let numberOfYears = 100  age
let totalNeeded = amountPerYear * numberOfYears
let message = "You will need" + totalNeeded + " " + item + "s to last the rest of your life"
}
Lab: Titleize
Write a function that:
 accepts a string as an argument
 splits apart the words in the string
 capitalizes each word
 returns a string with the first letter of each word capitalized e.g.
titilize("all dogs are good dogs") // => "All Dogs Are Good Dogs"
titilize("eveRY green bus drives fAst") // => "Every Green Bus Drives Fast"
titilize("FRIDAY IS THE LONGEST DAY") // => "Friday Is The Longest Day"
Titilize solution
Hint 1
Make a function to capitalize each word
function capitalize(word) {
let firstLetter = word[0].toUpperCase();
let restOfWord = word.slice(1).toLowerCase();
return firstLetter + restOfWord;
}
Hint 2
Split the words in the string into an Array of items
let wordArray = string.split(" ")
Solution
Loop over every item in the Array of words, capitalize each, and then add them to a new string
function capitalize(word) {
let firstLetter = word[0].toUpperCase();
let restOfWord = word.slice(1).toLowerCase();
return firstLetter + restOfWord;
}
function titilize(string) {
let wordArray = string.split(" ");
let newString = "";
let wordsModified = 0;
while (wordsModified < wordArray.length) {
let currentWord = wordArray[wordsModified];
let newWord = capitalize(currentWord);
newString = newString + " " + newWord;
wordsModified = wordsModified + 1;
}
return newString.trim();
}
More About Functions

 start with the challenge Write Reusable JavaScript with Functions
 continue through the challenge Assignment with a Returned Value
Links
 Functions
 Function example
 Calling a Function by Name
 Lab: One Nation, Divisible
 Divisible solution
 Shouter
 Lab: Capitalize
 Capitalize Lab Solution
 Passing Variables to Functions
 Four Function Syntaxes
 Lab: Age Calculator
 Flip it around!
 Solution
 Lab: Supply Calculator
 Supply Calculator Solution
 Lab: Titleize
 Titilize solution
 More About Functions
 Labs
 Links