String Interpolation


In the Classes lesson on static methods, we created a static method called .generatePassword() that would generate a random pin number for hospital employees to use. We typically think of pin numbers having 4 digits, and using the code in the example, numbers less than 1000 would display an output, e.g. 548, that would not contain a leading 0. I played around with the code a bit, which led me to this attempt to solve my question:

  static generatePassword() {
    let password = Math.floor(Math.random()*10000);
    if (password < 100) {
      password = '0' + password + Math.floor(Math.random() * 9);
      else if (password < 1000) {
      password = '0' + password;
      return password;
    } else {
      return password;

I was not sure if ‘0’ + 548 = 0548 would function as 0548 if I entered it into a prompt that checked if the two values were the same, so I went back to review string interpolation. The test I wrote returned a false value, and I assume that means that the program would not recognize those two as being the same. Is there a way I can address this issue?


i wouldn’t choice for this approach, it weakens the pin code

we could do this:

var val = Math.floor(1000 + Math.random() * 9000);

then then we 1000 till 9999. So we can’t get the first 1000 values. Which i don’t is a good either.

i like this solution:

var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);

we generate a random number between 0 and 10,000. Then take a substring to get get the last 4 digits.


Makes sense, thank you!