Doge Doge - 4 months ago 11
Javascript Question

JavaScript string generator not working

I'm new to javascript so don't judge me please :)

I have a real basic string generator, but it isn't working the way I want it to, it prints a 1 letter string (e.g "c") rather than a multi-letter string

var alphabet="abcdefghijklmnopqrstuvwxyz"

for (var i=0;i<alphabet.length;i++) {
var news=""
news=news+alphabet[Math.floor(Math.random()*alphabet.length)]
if (i==alphabet.length-1) {
console.log(news)
}
}

Answer

You have to declare and initialize the variable news outside the for loop. Declaring is not a problem when we use var to do that, because it will be hoisted to the top. But initialization is important. That has to be outside the for loop.

var alphabet="abcdefghijklmnopqrstuvwxyz";
var news="";

for (var i=0;i<alphabet.length;i++) {
  news=news+alphabet[Math.floor(Math.random()*alphabet.length)]
  if (i==alphabet.length-1) {
    console.log(news)
  }
}
Comments