5. Ten Simple JavaScript Exercises
Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in an array of numbers. For example, sum([1,2,3,4]) should return 10, and multiply([1,2,3,4]) should return 24.
by Lisa French
HTML
<h1>Ten Simple JavaScript Exercises</h1>
<a href="https://github.com/lisafrench/JavaScriptExercises">Read More Here</a>
<hr />
<h3>JavaScript Exercise 5:</h3>
<p>
Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in an array of numbers. For example, sum([1,2,3,4]) should return 10, and multiply([1,2,3,4]) should return 24.
</p>
<hr />
<h3>Console Log Out:</h3>
<div id="console-log"></div>
<hr />
JavaScript
//Hack to mimic console within JSFiddle
var consoleLine = "<p class=\"console-line\"></p>";
console = {
log: function (text) {
$("#console-log").append($(consoleLine).html(text));
}
};
//Begin exercise
var numbers = [1, 2, 3, 4];
function sum() {
var total = 0;
for (var i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
function multiply() {
//Setting total to one, since multiplying by zero will yeild zero
var total = 1;
for (var i = 0; i < numbers.length; i++) {
total = total * numbers[i];
}
return total;
}
console.log('The summed result of ' + numbers + ' is: ' + '"' + sum() + '"');
console.log('The multiplied result of ' + numbers + ' is: ' + '"' + multiply() + '"');