Sven Budak Sven Budak - 4 months ago 7
Javascript Question

Random Count in a "return" without many code

I google for a solution that allows me to generate a random number between 1 and 6. i found this: http://www.w3schools.com/jsref/jsref_random.asp

Now i tryed to use it in my code:

$scope.getUserImage = function (user) {
if (user.avatar) {
return user.avatar;
} else {
return '/images/icons/user-' + user.gender((Math.random() * 6) + 1) + '.svg';
}
};


but with this i get a error, it means that the user.gender isnt any function. I know this is a realy very basic question. I started new with JavaScript. I am a Designer normaly.

Answer

Since you want to add the strings together (called 'concatenate' since we're talking about strings), separate each with a + symbol. But the 1-6 logic is also wrong, you'll need to round those numbers down.

$scope.getUserImage = function (user) {
    if (user.avatar) {
        return user.avatar;
    } else {
        var randomNumberOneToSix = Math.floor(Math.random() * 6 + 1);
        return '/images/icons/user-' + user.gender + randomNumberOneToSix + '.svg';
    }
};

Bonus tip: w3schools is not a great resource. Add 'mdn' to every search and use Mozilla's excellent documentation for learning about web technologies.