Home > Blockchain >  Keep adding numbers into an array until a = 0
Keep adding numbers into an array until a = 0

Time:01-18

Hi I'm new to javascript and I'm sorry if my question is silly for you.

This question was solved with the following code:

let arr = [12, 6, 53]

let a
do {
  a = prompt("Enter a number")
  a = Number.parseInt(a)
  arr.push(a)
}

while (a != 0)

console.log(arr)

But, if I want that run the code if a == 0 rather than a != 0 i simply changed

while (a != 0)

into

while (a == 0)

But, it simply adds the number into the array

The problem

Can anyone please explain why this is happening?

I was expecting that the output should keep asking me to enter a number until a is equal to 0. I'm a bit silly (Please explain me if I'm right or wrong) I think that running the code until a != 0 and a == 0 should give the same answer in this code

CodePudding user response:

Can anyone please explain why this is happening?

I was expecting that the output should keep asking me to enter a number until a is equal to 0. I'm a bit silly (Please explain me if I'm right or wrong) I think that running the code until a != 0 and a == 0 should give the same answer in this code.


a != 0

Add items to the array if they do not equal 0 (else stop)

a == 0

Add items to the array if they equal 0 (else stop)


If you do not want the numbers that do not match adding to the array, then you need to also check this condition before inserting the value (before push).

let arr = [12, 6, 53];
let a;

do {
  a = prompt("Enter a number");
  a = Number.parseInt(a);
  if (a == 0) {
    arr.push(a)
  };
}
while (a == 0);

console.log(arr);

CodePudding user response:

First off, stop using do..while. Its usages are very limited and 0.01% of use cases where it actually makes sense are simply not worth the trouble of having yet another syntax construct in your codebase.

In your case, the use of do is not justified, because you want to check the condition (a!=0) before you perform the action (arr.push), not after it. The right pattern here is "loop forever break":

while (true) {
    let a = prompt("Enter a number")
    a = Number.parseInt(a)
    if (a !== 0) {
        break
    }
    arr.push(a)
}

Also note that 1) block-scoped variables belong inside the block, not outside it and 2) declaration without initialization (as in let a;) is a code smell and should be avoided.

Hope this helps.

  • Related