JavaScript JavaScript Numbers The Math Object Random Number Challenge – Solution

Is this bad practice?

I decided to use the same variable like this.

// Collect input from a user let userNumber = prompt('Please enter a maximum number');

// Convert the input to a number userNumber = +userNumber;

// Use Math.random() and the user's number to generate a random number let randomNum = Math.floor(Math.random() * userNumber) + 1;

// Create a message displaying the random number document.querySelector('main').innerHTML = ${randomNum} is a random number from 1 to ${userNumber};

The code in question is userNumber = +userNumber; Is this a bad habit to get into? I guess it depends if I want to use userNumber as a string later in the code?

Thanks.

I think it is a bad practice. First of all it is not explained properly. For ex.: How do we generate a random number, do we have to multiply, divide or substract? Secondly, we may get wrong results. For ex.: When I entered 9 the message was "9 is a random number between 1 and 9". It is not between them obviously.

2 Answers

Xavier Ritch
Xavier Ritch
11,097 Points

in my opinion, it's not a good practice. each variable name name should be semantic so your code is easily readable not only to others, but to yourself if and when you revisit your code in the future. So i think it's best to identify variables by naming them somewhat explicitly after whatever it is they are regarding.

That makes sense. Thank you.

You are touching upon the strength and weakness of JavaScript that it is a loosely typed language. If you find yourself in the camp that wants a strictly typed "JavaScript" language, then you might want to learn TypeScript after this course. But here in JavaScript just changing the type of the content of a variable does not change the meaning of its content, so your naming example is OK and not a bad practice.