If you want to calculate the total sum of numbers in an input array, you need to iterate through the array using a loop with an index starting from 0 up to array.length
. Within the loop, ensure that the condition is specific and checks if the index is less than the length of the array, like this:
let i = 0; i < ar.length; i++
The correct loop condition should be i < ar.length
, rather than just ar.length
, to avoid running into an infinite loop and to limit it to loop only for indices from 0 to ar.length
.
Here is a functional example with the corrected logic:
function simpleArraySum(ar) {
let acc = 0;
// Ensuring the index value is within the array length
for (let i = 0; i < ar.length; i++) {
// Applying a special condition
if (ar.length > 0 && ar[i] <= 1000) {
acc += ar[i]
}
}
return acc;
}
console.log(simpleArraySum([1, 2, 3]));
Why is your code returning undefined?
In your code, the loop statement is written as
let i = 0; ar.length; i++
With the condition set as ar.length
, it will always evaluate to true (assuming the array has a length greater than 0), leading to an endless loop. To rectify this, you have added a return statement inside the else block to terminate the loop. However, this return statement does not provide a value, resulting in the function returning undefined. This occurs because the return exits the function without returning anything.
As the loop progresses beyond the array length, attempting to access ar[i]
where i
exceeds the actual range results in undefined values. For such cases, the condition ar[i] <= 1000
becomes false, triggering the else block with a console log statement and an undefined return. Below is the updated code snippet including the console statement for illustration.
Your code execution with console statement.
function simpleArraySum(ar) {
let acc = 0;
for (let i = 0; ar.length; i++) {
if (ar.length > 0 && ar[i] <= 1000) {
acc += ar[i]
} else {
// Exiting here
console.log('Exiting loop: No return value provided');
return;
}
}
return acc;
}
console.log(simpleArraySum([1, 2, 3]));