Today I had very little time for code, so I wanted to do a very simple exercise: Generate a random number between 1 to 100, and in the case of JS also put that on the website. In both cases I used a bit of ChatGPT to fix this quickly. should do the same exercise again tomorrow and see if I can remember how to do it without!
My Code
Python
# Exercise: Print a random number between 1 and 100
import random
random_number = random.randint(1, 100)
print(random_number)
JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Random Number Generator</title>
</head>
<body>
<button id="generateButton">Generate Random Number</button>
<div id="randomNumber"></div>
<script>
document.getElementById("generateButton").onclick = function () {
let randomNumber = Math.floor(Math.random() * 100) + 1;
document.getElementById("randomNumber").textContent = randomNumber;
};
</script>
</body>
</html>
(Python actually suggested me ‘var’ here, but I don’t think that’s really used anymore, so I changed it to let)
Have a great day everyone, see you tomorrow! 🙋♂️
Top comments (3)
Since you're not changing the value of
randomNumber
after initialising it, you can also useconst
, which is preferred overlet
. (Constants are good.)I'm curious, why did you use
.textContent
instead of.innerText
? Is there a difference?@kaamkiya hi again!
const
/let
: good point. Since I learned to program with Python first I am not used to making that distinction. I guess I should just always useconst
and then just change them tolet
if I run into some kind of issue with that..textContent
/.innerText
: I actually never heard about.innerText
. What I saw in some tutorials was the use of.innerHTML
, but I figured that.textContent
would probably be the safer option if I'm not inserting any html tags. Do you think.innerText
would be even better to use?I don't know, I've only seen
textContent
used twice, but same withinnerText
. I doubt it matters, it's likely that one is just a reference to the other.