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

1

In the code below it would be interesting if I could define i as let and be able to keep pass as var, can you do that without declaring pass in a row above?

const randPass = () => {
    for (var i = 0, pass = ""; i < 8; i++) {
        pass = '${pass}${randChar()}';
    }
    return pass;
}
    
asked by anonymous 09.09.2017 / 19:54

1 answer

1

You can declare the two 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());

You do not have to define the variable outside the loop and then give return:

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());
    
09.09.2017 / 20:13