Hi I just learned some few basics of JavaScript (about ~5 hours in), I was wondering if there is anything that I can improve or optimize the code I made in some way? Thanks!
<html>
<body>
<h2>Adding numbers</h2>
<p>Start clicking buttons to add the numbers.</p>
<p><span id = "addNumber">0</span></p>
<script>
function addNumber(n) {
document.getElementById("addNumber").innerText =
document.getElementById("addNumber").innerText * 1 + n;
};
function resetNumber(){
document.getElementById("addNumber").innerHTML = 0
}
</script>
<button type = "button" onclick = "addNumber(1)" value= "d"> + 1 </button>
<button type = "button" onclick = "addNumber(5)" value= "d"> + 5 </button>
<button type = "button" onclick = "addNumber(10)" value= "d"> + 10 </button>
<button type = "button" onclick = "addNumber(15)" value= "d"> + 15 </button>
<button type = "reset" onclick = "resetNumber()"> Reset </button>
</body>
</html>
Hello,
Learning few basics of JS is unfortunately not enough by any means to look for code optimizations or best practices, but I can tell you this here
document.getElementById("addNumber").innerText =
document.getElementById("addNumber").innerText * 1 + n;
/* Here you can store the document.getElementById("addNumber") in a
variable and then use it accordingly */
/* try to make make the names you use in ids, classes and JS variables
more meaningful here addNumber is not a name of a HTML element id, it
can be a good name for function, you can change it to something like
counter*/
var counter = document.getElementById("addNumber") ;
counter.innerText = counter.innerText * 1 + n;
/* also mathematically speaking, counter.innerText * 1 is equal to
counter.innerText so either wrap the 1 + n in () or delete the * 1
if you delete the * 1 you will know have
*/
counter.innerText = counter.innerText + n; // which can be improved to
counter.innerText += n;
Use ;
consistently
and one last thing, although it is more if HTML thing really, remove the spaces between attributes , = and their respective values, it is considered bad practice to do so
There are also a lot of other improvements you can make like using addEventListener
method instead of inline event handler, arrow functions … but I am assuming you did not reach such subjects, yet
Important Note: please do not be discouraged by the amount of modifications I suggested, remember you still in the beginning of your JS journey, this is not an attempt by me to flex on you or anything, my advice is to learn more JavaScript and more advanced stuff before looking for best practices or code optimization techniques