0

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)
    }
}
1
  • 1
    Please indent your code properly when posting here. Commented Jul 17, 2016 at 18:23

2 Answers 2

2

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)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Minor mistake. Just define var news = ''; outside for loop. (Also, use semicolons).

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.