-1

I am working on a password generator but I keep getting RangeError: Maximum call stack size exceeded

What does this mean? Here is the code that gives this error...

The code is supposed to get the value of the text box when the "Get" button is clicked and use it as the "allowed charaters" when generating the random characters or random password then console.log it.

function makeid(length) {
  var result = [];
  console.log(makeid(5));
  
  var chars = document.getElementById("myInput").value;
  var characters = chars; //fix this
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result.push(characters.charAt(Math.floor(Math.random() *
      charactersLength)));
  }
  return result.join('');
}
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="makeid();">Get</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user9384
  • 27
  • 10
  • 1
    is `i < length` right ? – Manuel Spigolon Apr 08 '21 at 14:47
  • hmm idk? i think it should be... – user9384 Apr 08 '21 at 14:48
  • 2
    Look at each line of your code and follow the process through - hint, you've got a recursive call within the function itself. – Rory McCrossan Apr 08 '21 at 14:51
  • 2
    `console.log(makeid(5));` this is a recursive call without any condition... – ASDFGerte Apr 08 '21 at 14:51
  • 1
    I don't get why are you recursively calling `console.log(makeid(5));` – Andrew Apr 08 '21 at 14:51
  • OK so I looked at each line of my code and I got it to work! Turns out I needed to make a new function for logging the password... – user9384 Apr 08 '21 at 14:56
  • The error tells you the problem, but you need to know what it's saying `Maximum call stack size exceeded` - every time you make a `myFunction(args)` call, it adds the current code location to the "call stack" so that it knows where to go back to when that function `return`s. The call stack has a finite size. By calling `makeid` from within itself, you're adding a new entry to the call stack which no way to return - thus you fill it up (very quickly). The error is a check against such infinite loop code. – freedomn-m Apr 08 '21 at 15:23
  • @ManuelSpigolon normally, we would loop from `0` to `length-1` when doing `[i]` - but in this case they're doing `Math.floor(Math.random() * charactersLength)` where Math.random is `0..<1` so will never be 1 so `* charactersLength` will never be `1 * charactersLength` and with the `Math.floor` will always be `<= length-1` – freedomn-m Apr 08 '21 at 15:26
  • Or could just link to here, which explains it all: https://stackoverflow.com/questions/6095530/maximum-call-stack-size-exceeded-error?rq=1 – freedomn-m Apr 08 '21 at 15:27

1 Answers1

2

Remove the console.log(makeid(5))