Question

Create a function in JavaScript called "sum" that takes in an array as a parameter and...

Create a function in JavaScript called "sum" that takes in an array as a parameter and returns the sum of all of the EVEN numbers in a given array. Please note: the array passed in can have any data type, i.e. Strings, Numbers, Booleans, undefined, etc.

HINT: the expression typeof will help discern var types. For example if I have: var x = 4, and I do typeof(x) - the output would be "Number"

Example run:

sum([1, 4, 8, 10, 'q', true]) //output would be 22

sum([3 , 5, 7, true, false, 'po']) //output would be 0

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • We are using an array to enter inputs
  • We are passing the array to sum function
  • Comparing each element with it's data type
  • If it is number then checking for even number
  • If it is even then adding and returning total to output

==================== Start Program ====================

<!DOCTYPE html>
<html>
<body>

<script>
myArray = [1, 4, 8, 10, 'q', true]; //array to accept input
//myArray = [3 , 5, 7, true, false, 'po'];

var total = 0; //adding elements one by one
var result = sum(myArray); //calling sum function with array as parameter

document.write("Sum of Even Numbers: "+result); //printing the result

function sum(myArray) { //sum function
for(var i=0;i<myArray.length;i++){
   if(typeof myArray[i] === 'number'){ //checking for number data type
   if(myArray[i]%2==0){ //checking for even numbers
   total = total + myArray[i]; //adding even numbers
}
}
}
return total; //returning result to function call
}
</script>
</body>
</html>

==================== End Program ====================

Output: Sum of Even Numbers: 22

Add a comment
Know the answer?
Add Answer to:
Create a function in JavaScript called "sum" that takes in an array as a parameter and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT