JavaScript

Variables

A variable is a placeholder for storing and manipulating a value. You'll use variables in many different ways throughout your scripts.

If you've taken algebra, you've seen variables. If you haven't taken algebra, don't worry about it. Variables are simply the way JavaScript stores information.

For example, if you write

x = 2 then "x" is a variable that holds the value "2"

y = x + 3 then "y" will hold the value "5" (y = 2 + 3)

Types

  • string
  • numeric
  • Boolean (Member = true)
  • null Ė special keyword, that is treated as an "empty" variable

NOTE: This is distinct from a value of zero or an empty string where this is an actual value. The Null value is indicated in JavaScript by the term null.

Naming:

  • The first character in the name must be a letter (a-z or A-Z) or an underscore (_).
  • The rest of the name can be made up of letters (a-z or A-Z), numbers (0-9), or underscores (_).
  • Donít use spaces inside names. FirstName OK, but First Name is NOT OK!
  • Avoid "reserved words", words that are used for other purposes in JavaScript. For example, you couldnít call a variable alert or goto.
  • Case-sensitive - FirstName and firstName are not the same
  • Variables should describe what they are.

Valid Examples

  • year2000
  • First_Name
  • _people

Invalid Examples

  • $1000           // 1st character is not a letter (a-z or A-Z) or an underscore (_)
  • 1000             // 1st character is not a letter (a-z or A-Z) or an underscore (_)
  • &Me             // 1st character is not a letter (a-z or A-Z) or an underscore (_)
  • Date&Time   /* after the 1st character a name can be made up of letters (a-z or A-Z), numbers (0-9), or an underscores (_) ONLY! */

Declaring & "not" Declaring

In order to use variable, it is good programming style to declare it. Declaring a variable tells JavaScript that a variable of a given name exists so that the JavaScript interpreter can understand references to that variable name throughout the rest of the script.

Although it is possible to declare variables by simply using them, declaring variables helps to ensure that programs are well organized and helps to keep track of the scope of variables.

You can declare a variable using the var command:

var example;             NOTE: get into a habit of using semicolons

Ending Statements with a Semicolon?

NOTE: JavaScript doesn't require us to declare variables or end statements with semicolons. However, in the traditional programming languages C, C++, Java, and Perl each code statement must end with a semicolon. By getting into the habit of using semicolons you will have no problems when you get into other languages that require semicolons. The same principle applies to declaring variables.

In this line, you have defined a variable named example, which currently has no value. It is also possible to assign value to a variable when you declare it:

var example = "An Example";              NOTE: quotation marks for string

Here you have declared the variable named example and assigned a string value of "An Example" to it. Because JavaScript allows variables to also be declared on first use, the command example = "An Example" would also achieve the same result.

Note: the equal sign (=) used in assigning a value to a variable is known as an Assignment Operator. Assignment Operators are discussed later in this session.

var example = "An Example";

document.write(example);

  • var month = "June";       NOTE: quotation marks for string
  • month = "June";
  • var num;
  • var num = 9;
  • var nextWeek;
  • var NextWeek;                 NOTE: case-sensitive

If a JavaScript browser looks at a variable in a script and sees that the data after the = sign is not enclosed in quotation marks, and if it is not the word true or false, it creates a numeric value (also looks for 0 or 0x, otherwise assumes thatís a decimal).

Note: If you try to assign non-numeric data to a variable without putting that text in quotation marks, Navigator wonít like it. Youíll probably get a "xxx is not defined" error message (where xxx is the data you were trying to place into the variable).

Casting - Working with numbers and text combined

JavaScript is what is called a loosely typed programming language. In loosely typed languages, the type of a literal or variable is not defined when a variable is created and can, at times, change based on the context. By comparison, Java and C are not loosely typed.

You may have noticed that the + sign is used differently depending on the context it's in. If you place it between two numbers, the + sign will add the numbers:

2 + 2 = 4

10 + 5 = 15

If you put the plus sign between two words, the words will be joined together.

"two" + "two" becomes "twotwo"
"First word," + " second word." becomes "First word, second word."

And finally, if you put a word and a number together with the + sign, they will be joined as though they were both words.

"two" + 2 becomes "two2"
2 + "Ten" becomes "2Ten"

var num1 = 19;
var num2 = 96;
var total = num1 + num2;   // (total = = 115)

var text1 = "19";
var num1 = 96;
var total = text1 + num1;    // (total = = "1996")

var num2 = 19;
var text2 = "96";
var total = num2 + text2;    // (total = = "1996")

Ordinarily, you wouldn't want to do this, so when this happens, it's often the result of a mistake, where a number has previously been converted to a text string. This can happen when a number is retrieved from a cookie or if a number is entered into a form along with text characters.

Fortunately, if you run into a situation where JavaScript is treating numbers like text, there's a Method that can convert text string numbers back into a real numbers.

The parseInt() Method takes as an argument any text string that starts with a numeric character and it returns the number at the beginning as a number. It also removes any text that may have followed the number in the text string. Once the text number is converted back to a number you can safely use the + sign to add it to another number.

"2two" + 2 becomes "2two2"
parseInt("2two") + 2 is equal to 4

Two examples to test your "knowledge" (example1 & example2)