- Last week we talked about arrays and objects, which hold structured data.
- What can we do with that data? This is where functions come in.
- Today we'll talk about functions, parameters, scope, closures
- JavaScript is a functional language, so it's all about the functions!
- Functions can be difficult for people that are new to JavaScript, because they work differently than in other languages like Ruby, Java or C#.
- Functions are procedures that take arguments and return values.
- Think about them like a sheet of paper with instructions on it.
- A function has a name, an argument list, and a body.
- Arguments can be named anything you want
//Define a function
function saySomething(something) {
console.log(something);
}Execute a function by calling it's name with () and passing in arguments.
saySomething('Hello function!'); //logs 'hello function!'Functions can 'return' a value. A function evaluates to its return value when run.
(note to Ruby Developers: Ruby implicitly returns values. JS requires an explicit return statement if you are expecting a return value)
function add(number1, number2) {
number1 + number2;
}
var sum = add(1,2);
console.log(sum) // undefinedfunction add(number1, number2) {
return number1 + number2;
}
var sum = add(1,2);
console.log(sum); // 3All functions take any number of arguments, regardless of their declared signature.
function add(a,b) {
console.log(a,b)
}
add(1); // '1,undefined'
add(1,2,3,4,5) // '1,2'The arguments list simply creates variables that reference the arguments in order they were passed. For functions that take an unknown number of arguments, use the arguments object.
function add() {
var sum = 0;
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
add(1,2,3,4,5,6,7,8);Calculating gratutity is a repetitive task, so let's create a couple of functions that do the work for us.
- create a variable titled
billAmountand store a random number (ie: 100) - create a function titled
gratuity()- gratutity should:
- multiply the value of billAmount by 20%
hint: use 0.2 - return the value
- multiply the value of billAmount by 20%
- gratutity should:
- create a function titled
totalWithGrat()- totalWithGrat should:
- take in the amount as an argument
- call the gratutity function
- add that to the original bill amount
- return the total bill + gratuity
- totalWithGrat should:
- log the total (with gratuity) to the console
- append new total to the following phrase:
- "your total including gratuity is:"
- append new total to the following phrase:
- Limitation: You can only invoke the totalWithGrat function when logging the result
Mariel's Bonus Question
- Find a way to fix the decimal point to only 2 places, ie: 100.00
(hint: the answer is in the sentence above)
var billAmount = 100.58;
function gratutity(){
return billAmount * 0.2;
}
function totalWithGrat(amount){
return gratuity() + amount;
}
console.log("your total, including gratutity is: $" + totalWithGrat(billAmount).toFixed(2));- Functions are first class Objects in JavaScript.
- This means they can be:
- instantiated
- assigned
- reassigned
- and passed around just like any other variable.
- Again, think of them as a physical piece of paper.
Like other objects, functions can be assigned to variables.
var add = function(a,b){return a + b};The difference between declaring a function that way (Function assignment) and the function add(){} syntax we've been using (Function Declaration) is that the latter hoists both the declaration and definition. For example:
hoisted(); // logs "foo"
function hoisted() {
console.log("foo");
}notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log("bar");
};In the above example, we get a TypeError because notHoisted() is declared, but undefined until the assignment expression var notHoisted = .
- It's often handy to declare a function on the fly without a name.
- This is VERY common
var calculator = {
add: function(a,b) {
return a + b;
}
}
calculator.add(2,3) // 5So, what is the point of an Anonymous function?
- Cleaner code
- Scope management, used to create private scope (more on that later)
- Super useful with Closures (more on that later as well)
While, this might look strange, but you've already been doing this with Arrays and Objects. Functions are no different.
var arrayOfMystery = [
['anonymous','array'],
{ name: 'anonymous object' },
function(){ return 'Anonymous Function!'}
]
console.log(arrayOfMystery[0][1]) // array
console.log(arrayOfMystery[1].name) // anonymous object
console.log(arrayOfMystery[2]()) // anonymous function![ ]creates an array in memory{ }creates an object in memoryfunction(){ }creates an object in memory
Let's revisit Rock Paper Scissors...
- Define a
handsarray with the values 'rock', 'paper', and 'scissors'; - Define a function called
getHand()that returns a hand from the array usingparseInt(Math.random()*10)%3 - Define two objects for two players. Each player has
nameandgetHand()properties. - Define a function called
playRound()that- Takes two player objects as arguments
- Gets hands from each
- Determines the winner
- Logs the hands played and name of the winner.
- If its a tie, log the hands played and "it's a tie".
- Returns the winner object (null if no winner)
- Define a function called
playGame()that takes argumentsplayer1,player2, andplayUntil.- Play rounds until one of the players wins
playUntilhands - When one player has won enough games, return the winning player object
- Play rounds until one of the players wins
- Play a game to 5 wins
Mariel's Bonus Questions
- Define a function caled
playTournament()- Take 4 players and
playUntilas arguments - Play a game between the first two players, and the second two players
- Play a game between the winners of the first round.
- Announce the tournament winner's name "[name] is the world champion";
- Take 4 players and
###Due on 7/28/2016
- Complete the new Rock Paper Scissors Challenge
- Push completed to GitHub with the name:
RPS_functions_YOUR_INITIALS_HERE
- Push completed to GitHub with the name:
###Due on 8/2/2016
- Complete the JavaScripting Module at NodeSchool
- Upload a completed screenshot to Slack
- Read the You Don't Know JS book on closures. (chapters 1 - 5)
- Complete the code examples
- push to github with the name:
YDKJS_closures_YOUR_INITIALS_HERE