wymyszony wymyszony - 5 days ago 5
Javascript Question

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);

Answer

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>

Comments