Javascript Lesson 2: Variables

Variables are objects that store values. They are used to perform calculations in programs that range from very complex equations to simple addition.

Below this paragraph, you'll find a program that performs a simple calculation based on user input. There is an explanation of the source code to the left of the program.

-Line 1 starts with the creation of a "label". Labels can be used to create text that denotes the use of various html elements.

In this case, we are creating a label for a text box where the user will enter the "first number" for our javascript program.

-Line 2 is where we create the text box that is needed for our function. The input tag creates a text box, and the section type="number" makes sure that only numbers can be entered into the text box.

-Lines 4 and 5 Repeat the previous steps, but this time we create a label and text box for our second number.

-Line 7 creates a button for use in our function. The section onclick = "Calculator()" will call our Javascript function every time the button is clicked.

-Lines 11 and 12 Start with our script tag and Function definition. Anything entered between the script tags will be interpreted by your web page as code.

In order to create our function, we have to write the word function and then give it a name followed by parentheses (). In this case, it is called Calculator(). The contents of a function must be contained within brackets { }.

-Line 15 has a declaration for three different variables that we will need. 'X' , which will store the first number entered by the user,
'Y' , which stores the second number, and 'result', which stores the end result of the calculation.

-Lines 17 and 18 give our variables X and Y a value based on the input from our text boxes.

After the "=", we use a function called "parseInt", which ensures that the input has been converted into a number.

Within the parentheses of the parseInt function, we use the line document.getElementById("First_Num").value to set our variable to the value of our text box "First_Num" and "Second_Num".

-Line 20 sets the value of result to X + Y.

-Line 21 uses the function document.getElementById().innerHTML to append our variable result to the element labeled "calculation". Earlier, we created a header with the ID of "calculation", so now our variable result will be displayed within the header.

You can copy the code to the right into the body of your website in order to use it.