"Give me a beginner-friendly JavaScript LeetCode-style problem that uses arrays and a loop, and explain it simply."
Problem:
Given an array of numbers, return the sum of all the numbers in the array.
Example:
Input: [1, 2, 3, 4]
Output: 10
Explanation:
Add all the numbers together and return the total.
function sumArray(nums) {
let total = 0;
for (let i = 0; i < nums.length; i++) {
total += nums[i];
}
return total;
}
// Example test
console.log(sumArray([1, 2, 3, 4]));
<!DOCTYPE html>
<html>
<head>
<title>Sum Array</title>
</head>
<body>
<h2>Sum of Array Example</h2>
<script>
function sumArray(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
document.write("Sum: " + sum);
}
sumArray([1, 2, 3, 4]);
</script>
</body>
</html>