JavaScript Resources

Syntax of Variables

  • When creating a variable, always precede the variable name with the term "var". This lets the browser know that you are creating and naming a variable. For example:

    var password

  • When creating a variable, it is not necessary to give it an initial value, but unless you have a particular reason for not doing so, it is pointless. For example:

    var age is o.k.
    var age = "30" makes more sense

  • Choose a descriptive name. If you are asking a user to submit their age to you, it is a better idea to name that variable "age" than to call it "x" or "data" or "userinfo". As your scripts grow longer, this will make it easier to immediately identify what type of information is being stored in particular variables.

  • Use unique names. If you have more than one variable in your script, you will want those variables to be distinct from each other. If you are requesting a first name from a user and also a last name, you should give those variables the names of "first" and "last" respectively. Otherwise, you will overwrite data.

  • You cannot include white space in a variable name.

    var firstname is good.
    var first name is bad.

  • Do not include symbols except for the underscore "_" character. The underscore character is commonly used to separate words when more than one word is more descriptive as a name for a variable.

    var first_name = "Jebeze"

  • Using more than word as a variable name is such a common occurrence in JavaScript that it has become customary to use the interCap method, that is, to not use spaces or the underscore character to separate words, but to instead capitalize all additional words after the first word.

    var firstName = "Jebeze"
    var mothersMaidenName = "Irabu"

  • You can include numbers in a variable name, but you cannot begin a variable name with a number. You may want to use numbers when you are requesting similar, but slightly different information from a user. For example, a series of prompt boxes used to gather ordering information from a user might look like this:

    var item1 = window.prompt("What item would you like to order?")
    var item2 = window.prompt("What item would you like to order?")
    var item3 = window.prompt("What item would you like to order?")

  • Variable names are case-sensitive. For example, the following are all distinct variables:

    var name = "Jebeze"
    var NAME = "Jebeze"
    var Name = "Jebeze"

  • You cannot use a word or term that has special meaning to JavaScript. For example:

    var var = "some value"
    var alert = "some value"
    var prompt = "some value"

    These are all terms that will confuse the web browser. There are many other words as well. See Appendix B (pp.951) in the JavaScript Bible for a complete list.