wymyszony
wymyszony

Reputation: 517

JavaScript function returning "undefined"

I wrote a simple code to choose random name from four, using "random_word();" function and it doesn't work. It says:"undefined". Can anyone explain me why and help to fix it? Thanks for all help.

var randomWord;

var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";

function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}

random_word();

document.write(randomWord);

Upvotes: 2

Views: 2827

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

You make randomWord to a private variable of the function with a var statement. Without, you could use the global variable for the result.

function random_word() {
    randomWord = word[Math.floor(Math.random() * word.length)];
}

var randomWord;
    word = ["Michael", "Simon", "Peter", "Mark"];

random_word();
document.write(randomWord);

A better style and more concise would be the return of the selected item. An even better version, would be if you use the array as parameter as well, because you could use the function for other arrays as well.

function getRandomItem(array) {
    return array[Math.floor(Math.random() * array.length)];
}

var words = ["Michael", "Simon", "Peter", "Mark"];

document.write(getRandomItem(words));

Bonus, add random name with interval.

function getRandomItem(array) {
    return array[Math.floor(Math.random() * array.length)];
}

var words = ["Michael", "Simon", "Peter", "Mark"];

setInterval(function () {
    document.getElementById('names').innerHTML += getRandomItem(words) + '<br>';
}, 2000);
<div id="names"></div>

Upvotes: 3

Ram
Ram

Reputation: 144739

The local variable randomWord in the random_word function context has nothing to do with the randomWord declared in the outer context. If you want to reset the value of the outer context randomWord variable then you should drop the var keyword in your function.

function random_word(){
    randomWord = word[Math.floor(Math.random()*word.length)]
}

But this is not a good way of programming. Ideally the function should return a value.

function random_word(){
  return word[Math.floor(Math.random()*word.length)];
}

var randomWord = random_word();
var anotherRandomWord = random_word();

Upvotes: 3

Yaser
Yaser

Reputation: 5719

You are using var keyword in your function which creates a local variable. When you get out of that function the global one is not set.

Use this instead:

function random_word(){  
    randomWord = word[Math.floor(Math.random()*word.length)]
}

Upvotes: 0

Related Questions