Once you have completed the first phase of your programming and you have everything working, it is now time to enhance the code for future use, to make it better or more flexible.
Particularly true for beginner developers, it is important to comment your code so that if you or someone else needs to refer to it several months later to determine what was done or why it was done. You will find out that the more proficient you become at programming, the less you will have a tendency to comment your code because you will know the code better and you will make your code more self-commenting through the use of descriptive names of variables, functions, methods, etc.
<script> function addNumbers() { /*Store references of the three text fields in variables so that they don't have to be writing in a long format later in the code.*/ var firstNum = document.getElementById("firstNumber").value; var secondNum = document.getElementById("secondNumber").value; /*The built-in Number() method was used to convert the string values to text values. Also, the two text fields results were added together and store as the value property of the third text field (total). */ document.getElementById("total").value = Number(firstNum) + Number(secondNum); //alert(typeof(firstNum)); //alert(typeof(secondNum)); //alert(typeof(sum)); } </script>
NOTE: Comments are not executed when the program runs, so you can add as many as you like.
As a beginner developer you should always strive to make your code more flexible by separating the code from the tag elements, using functions, etc.
It is best practice not to have code "coupled" with the tag elements on the page. One way to decouple your code is to use event listenering instead of simply events attributes.
<button id="addNumberButton">Add Numbers</button>
IMPORTANT CONCEPT TO REMEMBER: Instead of invoking the addNumber() function from the button, an addEventHandler method will be used so that it will add this functionality to the <button> tag from a distance so the code is made more flexible. For example, now you can cut and paste the code in the script tag and paste it in another document and link it to a different element by using the tag id attribute. Let's see how this works.
<script> var addButton = document.getElementById("addNumberButton") addButton.addEventListener("click", addNumbers) function addNumbers() { // Code deleted here so that you could see structure better.
// DO NOT delete code in example. } </script>
Once you have completed the basic needs of your project, you may want to add some additional features or improvement to your project. For example, you may want to add the ability to: