Skip to content

Instantly share code, notes, and snippets.

@alexkahn
Last active August 29, 2015 14:15
Show Gist options
  • Save alexkahn/3c02f3f6dce3137994de to your computer and use it in GitHub Desktop.
Save alexkahn/3c02f3f6dce3137994de to your computer and use it in GitHub Desktop.
Function examples
// 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