Search code examples
javascriptnode.jsvariablesprompt

Prompt a request and reassign the value according to condition


Im using Javascript/Node.js

i want to ask the user to input a number. I want to check some condition on it: it should not be a string and it should be a number greater than 25. Until the condition is met, the question "input a number..." should be prompted. When the condition is met, it should exit the loop and the new value of "P" should be assigned.

The loop works fine, but when it ends and i console.log(p), the value is not updated. If i console.log(a) inside the loop, the value is logged correctly. What im doing wrong?

    let p = prompt('Input a number => ');
const checkP = (a) => {
  while (isNaN(a%2) || a > 25) {
    a = prompt('Input a number or a number less than 25 => ');
  }
};
checkP(p);
console.log(p);

Solution

  • You are modifying variable a, which is passed parameter, therefore it is only available inside checkP function, nor it can mutate p

    Change this:

    let p = prompt('Input a number => ');
    const checkP = (a) => {
        while (isNaN(a % 2) || a > 25) {
            a = prompt('Input a number or a number less than 25 => ');
        }
    };
    checkP(p);
    console.log(p);
    

    To this:

    let p = prompt('Input a number => ');
    const checkP = () => {
        while (isNaN(p % 2) || p > 25) {
            p = prompt('Input a number or a number less than 25 => ');
        }
    };
    checkP();
    console.log(p);