Last active
September 2, 2019 07:15
-
-
Save LeanSeverino1022/4ababeeceaf169b8fa30f8fc2b234f74 to your computer and use it in GitHub Desktop.
Compute Sum #vanillajs
This file contains hidden or 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
//if you want the old way: | |
function sum(){ | |
var sum =0; | |
for(var i=0;i<arguments.length;i++){ | |
sum += arguments[i]; | |
} | |
return sum; | |
} | |
sum(1,2); // returns 3 | |
sum(1,2,3); // returns 6 |
This file contains hidden or 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
/*The rest parameter syntax allows us to represent an indefinite number of arguments as an array */ | |
function sum(...theArgs) { | |
return theArgs.reduce((previous, current) => { | |
return previous + current; | |
}); | |
console.log(sum(1, 2, 3)); | |
// expected output: 6 | |
console.log(sum(1, 2, 3, 4)); | |
// expected output: 10 |
This file contains hidden or 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
//As a helper function - Returns the sum of all values in a given array. | |
const arrSum = arr => arr.reduce((a,b) => a + b, 0) | |
// arrSum([20, 10, 5, 10]) -> 45 | |
//function above is identical to | |
arrSum = function(arr){ | |
return arr.reduce(function(a,b){ | |
return a + b | |
}, 0); | |
} | |
//src: https://codeburst.io/javascript-arrays-finding-the-minimum-maximum-sum-average-values-f02f1b0ce332 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment