I’m going to take advantage of the DOM to do the adding for me!
let numbers = [4, 10, 5, 7, 13, 20];
function div (width) {
let el = document.createElement("div");
el.style.display = 'inline-block';
if (width) el.style.width = `${width}px`;
return el;
}
let container = document.body.appendChild(div());
numbers.forEach(num => container.appendChild(div(num)));
let total = container.offsetWidth;
container.remove();
console.log(`Sum of array values is ${total}`);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum an Array of Numbers</title>
<!--<link rel="stylesheet" href="sumArrStyles.css">-->
</head>
<body>
<h1>Sum an array of numbers</h1>
<br>
<h2>Instructions:</h2>
<p>Create an array of numbers and add them all together. The results should be in the console.</p>
<script>
// Create an array of numbers
let numbers = [
4,
10,
5,
7,
13,
20,
];
// Create a variable to hold the sum
let sum = 0;
// Loop over the array, adding each number to the sum
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// Put the result in the console
console.log("Sum of array values is: " + sum);
</script>
</body>
</html>