Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Numbers The Math Object Random Number Challenge – Solution

Ed Farias
Ed Farias
4,476 Points

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

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.

Ed Farias
Ed Farias
4,476 Points

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.