Last active
August 29, 2015 14:15
-
-
Save alexkahn/3c02f3f6dce3137994de to your computer and use it in GitHub Desktop.
Function examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function example | |
// make a sum function that takes an array | |
// but it assumes the array will contain numbers | |
function sum(values) { | |
if (!(values instanceof Array)) { | |
throw new Error('Values must be an array'); | |
} | |
var i = 0; | |
var l = values.length; | |
var total = 0; | |
for (i; i < l - 1; i++) { | |
total += values[i]; | |
} | |
return total; | |
} | |
// make a function that takes an average of | |
// an array of values | |
function average(values) { | |
var total = sum(values); | |
n = values.length; | |
return total/n; | |
} | |
// use the function: | |
var avg = average([1,2,3,4,5,6]); | |
console.log(avg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment