Lesson 2, Intro to Variables:
A variable can only begin with either a letter or underscore ( _ ). The rest of the variable name may contain letters and numbers, the underscore character ( _ ), and a dollar sign ( $ ). Reserved words can't be used for variable names.
Unlike some other programming languages, in JavaScript you do not declare a type for variables. For example, you do not say that variable x must be a string or a number. The variable automatically changes its type as needed. To declare variables in JavaScript you use the reserved word: "var" as in the following example where we assign a text string to the variable x:
var x = "abcdefg"
Likewise, if we want to assign a number to a variable, it is done like so:
var y = 2
Take notice of the difference when declaring a number and when declaring a text string. for example when you are declaring a text string you use quotation marks and when you are declaring a number as a value, you use no quotation marks. If you were to use quotation marks when declaring a number, the number would then assume the value of a string and would have no numerical value. For example consider the following:
var x = 2;
var y = 5;
In the above example, if we were to add x + y, it would return the value of 7.
Now consider:
var x = "2"
var y = "5"
Whereas in this example, if we were to add x + y, it would return a concatenated string of 25.
So, the basic lesson here is that if you want to be able to use numbers mathematically, do not use quotes.
Okay, a few of you may be still wondering what "concatenated" means and for the sake of being thorough, as this guide is designed to help anyone learn JavaScript, Concatenate means simply to link together in a series or chain or to join together.
So, using the above example, when 2 and 5 are concatenated or
linked together
, you get 25 and when they are
added together
(no quotation marks), you will get 7. That concludes our introduction to variables. You will learn more as the guide progresses.
Example script:
Okay, Now we should be ready to write a simple script using what we have learned.
var text1 = "This is an example of ";
var text2 = "concatenating text using a plus sign.";
document.write(text1 + text2);
What we have above, are two separate text strings each stored in a different variable. This is commonplace in Javascript in situations where you might store a person's name in one variable and a common greeting in another variable. You may then concatenate them to make a personalized greeting with the user's name. If you were to exicute the code, it would simply display the sentence: This is an example of concatenating text using a plus sign.
Javascript Discussion
- - Google Chrome / Mozilla?
- - Delete text after focus c
- - Statistics
- - Tabs using javascript
- - Select all values in te
Javascript Source Code
- - E-mail Validation
- - Required Fields
- - Alert User Depending On Browser
- - All Details About Browser
- - More Browser Detection





