Is it possible to use Let and var in the same loop for?

Asked

Viewed 66 times

1

In the code below it would be interesting if I could define i as Let and be able to keep pass as var, have to do this without being declaring pass in a line above?

const randPass = () => {
    for (var i = 0, pass = ""; i < 8; i++) {
        pass = `${pass}${randChar()}`;
    }
    return pass;
}

1 answer

2


You can declare both with let using ,, on the same line. But if you want the function return to be pass then you have to give return inside the loop like this:

function randChar() {
  return Math.random().toString(36).slice(-1);
}

const randPass = () => {
  for (let i = 0, pass = ""; i < 8; i++) {
    pass = `${pass}${randChar()}`;
    if (i == 7) return pass;
  }
  
}

console.log(randPass());

Otherwise you have to leave the variable out of the loop and then re-turn:

function randChar() {
  return Math.random().toString(36).slice(-1);
}

const randPass = () => {
  let pass = ""
  for (let i = 0; i < 8; i++) {
    pass = `${pass}${randChar()}`;
  }
  return pass;
}

console.log(randPass());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.