Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Value of variable keeps reverting back to null JavaScript

I am working with this following code in order to make a simple password generator. The issue I am facing is that when the passwordLength function is run, and no answer is given, it goes through the given process, including alerting me: "Incorrect value. Please choose a number between 8 and 128." Following that prompt the function is re-run. However, when I re-enter my value(this time with a correct value). It goes through to the "return lengthInput", but doesn't return the value I just input. It returns the value that was generated in the first loop. In this case, that would be null. How do I get it to return the value I just typed in rather than sending the value that was previously run through the loop?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should always create an SO snippet to present your actual problem. In your case you forgot to store the returned value of the recursion call in the variable lengthInput:

const passwordLength = function() {
  var lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.");

  if (lengthInput < 8 || lengthInput > 128) { 
    window.alert("Incorrect value. Please choose a number between 8 and 128.");
    lengthInput=passwordLength();
  }

  return lengthInput;
};

console.log(passwordLength())

The code in this snippet is still overcomplicated, as it will unnecessarily go into a recursion. But at least it will use the latest "legal" value for lengthInput.

A simpler solution to your problem might be:

const passwordLength = function() {
  var lengthInput;
  while ((lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.")), lengthInput < 8 || lengthInput > 128)
    window.alert("Incorrect value. Please choose a number between 8 and 128.");
  return lengthInput;
};

console.log(passwordLength())

Or even:

const passwordLength = function() {
  do var lengthInput = window.prompt("How long do you want your password to be? Please choose a number between 8 and 128.");
  while (lengthInput < 8 || lengthInput > 128)
  return lengthInput;
};

console.log(passwordLength())

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!