# Curious if theres a way to run a code like this?

let count = [6 + 5 + 6 + 0 + 9 + 8];
console.log(count);
for (let i = 0; i < count; i++) {
console.log(count[i]);
if (count[i] === count[17]){
break;
}
}
// So I’m very new to this and I was just wondering if there is a way, using a loop, to get mid way into a math problem in an array, for example 6+5+6 = 17, recognize i=17, have that be a breaking condition, and then end the loop and log 17?
is this possible? like I said I’m very new and was just theory crafting an idea tonight.

Hi there and welcome to the forums!

This is absolutely possible but it requires a slight change to how you’re working it. At the moment you have the array `count`, which is an array with a single element, the sum that you have given. This sum is calculated right when count is declared and so essentially you just have `count = [34]`, which isn’t what you want. You want an array of the digits, and then to sum them inside the look to check for your conditions. In addition, you don’t want to know where `i=17` as `i` is your index checker i.e. `i`’s max value should be the number of elements in the count array. So lets rewrite this a little.

``````let count = [6, 5, 6, 0, 9, 8];
let sum = 0;
``````

This is just making the count array into an array we can use, and adding a sum variable we can increment to have a running sum.

``````for (let i = 0; i < count.length; i++) {
sum += count[i];
if (sum === 17) {
break;
}
``````

This loop declares an element `i`, makes sure it can’t get larger than the length of `count` and increments it each time. Then it adds the `i`th element of `count` to the `sum` variable we declared, meaning we’ll have a running total. Then the `if` statement runs to check if our running total is 17 and if so, exits the loop.

To see this in action, run the codebyte below, and edit the if statement to see how it changes with different numbers being checked.

let count = [6, 5, 6, 0, 9, 8] let sum = 0; for (let i = 0; i < count.length; i++) { console.log(`Element at position \${i} is: `, count[i]); sum += count[i]; if (sum === 17) { break; } } console.log(`The final sum is:`, sum);
2 Likes

Oh i see, i understand now what i did wrong, that’s great thanks very much for reviewing that for me!