Variables, Arrays and Operators

In this lesson of the JavaScript tutorial, you will learn...
  1. To create, read and modify JavaScript variables.
  2. To work with JavaScript arrays.
  3. To work with JavaScript operators.

JavaScript Variables

Variables are used to hold data in memory. JavaScript variables are declared with the var keyword.

var age;

Multiple variables can be declared in a single step.

var age, height, weight, gender;

After a variable is declared, it can be assigned a value.

age = 34;

Variable declaration and assignment can be done in a single step.

var age = 34;

A Loosely-typed Language

JavaScript is a loosely-typed language. This means that you do not specify the data type of a variable when declaring it. It also means that a single variable can hold different data types at different times and that JavaScript can change the variable type on the fly. For example, the age variable above is an integer. However, the variable strAge below would be a string (text) because of the quotes.

var strAge = "34";

If you were to try to do a math function on strAge (e.g, multiply it by 4), JavaScript would dynamically change it to an integer. Although this is very convenient, it can also cause unexpected results, so be careful.

Storing User-Entered Data

The following example uses the prompt() method of the window object to collect user input. The value entered by the user is then assigned to a variable, which is accessed when the user clicks on one of the span elements.

Code Sample: VariablesArraysOperators/Demos/Variables.html

<html>
<head>
 <title>JavaScript Variables</title>
 <script type="text/javascript">
  //Pop up a prompt
  var USER_COLOR = window.prompt("Enter a color.", "");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = 'red';">Red</span> |
 <span onclick="document.bgColor = 'white';">White</span> |
 <span onclick="document.bgColor = 'green';">Green</span> |
 <span onclick="document.bgColor = 'blue';">Blue</span> |
 <span onclick="document.bgColor = USER_COLOR;">
 <script type="text/javascript">
  document.write(USER_COLOR);
 </script>
 </span>
</p>
</body>
</html>
Code Explanation

As the page loads, a prompt pops up asking the user to enter a color.

This is done with the prompt() method of the window object. The prompt() method is used to get input from the user. It takes two arguments:

  1. The message in the dialog box (e.g., "Enter a color.").
  2. The default value that appears in the text box. In the example above this is an empty string (e.g, "").

If the OK button is pressed, the prompt returns the value entered in the textbox. If the Cancel button or the close button (the red X) is pressed, the prompt returns null. The line below assigns whatever is returned to the variable USER_COLOR.

var USER_COLOR = window.prompt("Enter a color.", "");

A script block with a call to document.write() is then used to output the color entered by the user. This output is contained within a span element, which has an onclick event handler that will be used to turn the background color of the page to the user-entered color.

<span onclick="document.bgColor = USER_COLOR;">
 <script type="text/javascript">
  document.write(USER_COLOR);
 </script>
</span>

Arrays

An array is a grouping of objects that can be accessed through subscripts. At its simplest, an array can be thought of as a list. In JavaScript, the first element of an array is considered to be at position zero (0), the second element at position one (1), and so on. Arrays are useful for storing data of similar types.

Arrays are declared using the new keyword.

var myarray = new Array();

It is also possible and very common to use the [] literal to declare a new Array object.

var myarray = [];

Values are assigned to arrays as follows.

myarray[0] = value1;
myarray[1] = value2;
myarray[2] = value3;

Arrays can be declared with initial values.

var myarray = new Array(value1, value2, value3);
//or, using the [] notation:
var myarray = [value1, value2, value3];

The following example is similar to the previous one, except that it prompts the user for four different colors and places each into the USER_COLORS array. It then displays the values in the USER_COLORS array in the spans and assigns them to document.bgColor when the user clicks on the spans.

Unlike in some languages, values in JavaScript arrays do not all have to be of the same data type.

Code Sample: VariablesArraysOperators/Demos/Arrays.html

<html>
<head>
 <title>JavaScript Arrays</title>
 <script type="text/javascript">
  //Pop up four prompts and create an array
  var USER_COLORS = new Array();
  USER_COLORS[0] = window.prompt("Choose a color.", "");
  USER_COLORS[1] = window.prompt("Choose a color.", "");
  USER_COLORS[2] = window.prompt("Choose a color.", "");
  USER_COLORS[3] = window.prompt("Choose a color.", "");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = USER_COLORS[0];">
 <script type="text/javascript">
  document.write(USER_COLORS[0]);
 </script>
 </span> |
 <span onclick="document.bgColor = USER_COLORS[1];">
 <script type="text/javascript">
  document.write(USER_COLORS[1]);
 </script>
 </span> |
 <span onclick="document.bgColor = USER_COLORS[2];">
 <script type="text/javascript">
  document.write(USER_COLORS[2]);
 </script>
 </span> |
 <span onclick="document.bgColor = USER_COLORS[3];">
 <script type="text/javascript">
  document.write(USER_COLORS[3]);
 </script>
 </span>
</p>
</body>
</html>
Code Explanation

As the page loads, an array called USER_COLORS is declared.

var USER_COLORS = new Array();

The next four lines populate the array with user-entered values.

USER_COLORS[0] = window.prompt("Choose a color.", "");
USER_COLORS[1] = window.prompt("Choose a color.", "");
USER_COLORS[2] = window.prompt("Choose a color.", "");
USER_COLORS[3] = window.prompt("Choose a color.", "");

The body of the page contains a paragraph with four span tags, the text of which is dynamically created with values from the USER_COLORS array.

Associative Arrays

Whereas regular (or enumerated) arrays are indexed numerically, associative arrays are indexed using names as keys. The advantage of this is that the keys can be meaningful, which can make it easier to reference an element in an array. The example below illustrates how an associative array is used.

Code Sample: VariablesArraysOperators/Demos/AssociativeArrays.html

<html>
<head>
 <title>JavaScript Arrays</title>
 <script type="text/javascript">
  var BEATLES = [];
  BEATLES["singer1"] = "Paul";
  BEATLES["singer2"] = "John";
  BEATLES["guitarist"] = "George";
  BEATLES["drummer"] = "Ringo";
 </script>
</head>
<body>
<p align="center">
 <script type="text/javascript">
  document.write(BEATLES["singer1"]);
  document.write(BEATLES["singer2"]);
  document.write(BEATLES["guitarist"]);
  document.write(BEATLES["drummer"]);
 </script>
</p>
</body>
</html>

Array Properties and Methods

The tables below show some of the most useful array properties and methods. All of the examples assume an array called BEATLES that holds "Paul", "John", "George", and "Ringo".

var BEATLES = ["Paul", "John", "George", "Ringo"];
Array Properties
Property Description Example
length Holds the number of elements in an array. BEATLES.length // 4
Array Methods
Property Description Example
join(delimiter) Returns a delimited list of the items indexed with integers in the array. The default delimiter is a comma. BEATLES.join(":") // Paul:John:George:Ringo
pop() Removes the last item in an array and returns its value. BEATLES.pop() // Returns Ringo
shift() Removes the first item in an array and returns its value. BEATLES.shift() // Returns Paul
slice(start, end) Returns a subarray from start to end. If end is left out, it includes the remainder of the array. BEATLES.slice(1 ,2) //Returns [John, George]
splice(start, count) Removes count items from start in the array and returns the resulting array. BEATLES.splice(1, 2) //Returns [Paul, Ringo]

JavaScript Operators

Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
++ Increment by one
-- Decrement by one
Assignment Operators
Operator Description
= Assignment
+= One step addition and assignment (a+=3 is the same as a=a+3)
-= One step subtraction and assignment (a-=3 is the same as a=a-3)
*= One step multiplication and assignment (a*=3 is the same as a=a*3)
/= One step division and assignment (a/=3 is the same as a=a/3)
%= One step modulus and assignment (a%=3 is the same as a=a%3)
String Operators
Operator Description
+ Concatenation (var greeting = "Hello " + firstname;)
+= One step concatenation and assignment (var greeting = "Hello "; greeting += firstname;)
Ternary Operator
Operator Description
?: Conditional evaluation (var evenOrOdd = (number % 2 == 0) ? "even" : "odd";)

The following code sample shows these operators in use.

Code Sample: VariablesArraysOperators/Demos/Operators.html

<html>
<head>
 <title>JavaScript Operators</title>
 <script type="text/javascript">
  var USER_NUM1 = window.prompt("Choose a number.", "");
  alert("You chose " + USER_NUM1);
  var USER_NUM2 = window.prompt("Choose another number.", "");
  alert("You chose " + USER_NUM2);
  var NUMS_ADDED = USER_NUM1 + Number(USER_NUM2);
  var NUMS_SUBTRACTED = USER_NUM1 - USER_NUM2;
  var NUMS_MULTIPLIED = USER_NUM1 * USER_NUM2;
  var NUMS_DIVIDED = USER_NUM1 / USER_NUM2;
  var NUMS_MODULUSED = USER_NUM1 % USER_NUM2;
 </script>
</head>
<body>
<p style="text-align:center; font-size:large">
 <script type="text/javascript">
  document.write(USER_NUM1 + " + " + USER_NUM2 + " = ");
   document.write(NUMS_ADDED + "<br/>");
  document.write(USER_NUM1 + " - " + USER_NUM2 + " = ");
   document.write(NUMS_SUBTRACTED + "<br/>");
  document.write(USER_NUM1 + " * " + USER_NUM2 + " = ");
   document.write(NUMS_MULTIPLIED + "<br/>");
  document.write(USER_NUM1 + " / " + USER_NUM2 + " = ");
   document.write(NUMS_DIVIDED + "<br/>");
  document.write(USER_NUM1 + " % " + USER_NUM2 + " = ");
   document.write(NUMS_MODULUSED + "<br/>");
 </script>
</p>
</body>
</html>
Code Explanation

The file above illustrates the use of the concatenation operator and several math operators. It also illustrates a potential problem with loosely-typed languages. This page is processed as follows:

  1. The user is prompted for a number and the result is assigned to USER_NUM1.
  2. An alert pops up telling the user what number she entered. The concatenation operator (+) is used to combine two strings: "You chose " and the number entered by the user. Note that all user-entered data is always treated as a string of text, even if the text consists of only digits.
  3. The user is prompted for another number and the result is assigned to USER_NUM2.
  4. Another alert pops up telling the user what number she entered.
  5. Five variables are declared and assigned values.
    var NUMS_ADDED = USER_NUM1 + USER_NUM2;
    var NUMS_SUBTRACTED = USER_NUM1 - USER_NUM2;
    var NUMS_MULTIPLIED = USER_NUM1 * USER_NUM2;
    var NUMS_DIVIDED = USER_NUM1 / USER_NUM2;
    var NUMS_MODULUSED = USER_NUM1 % USER_NUM2;
  6. The values the variables contain are output to the browser.

So, 5 + 4 is 54! It is when 5 and 4 are strings, and, as stated earlier, all user-entered data is treated as a string. In the lesson on JavaScript Functions, you will learn how to convert a string to a number.

Variables, Arrays and Operators Conclusion

In this lesson of the JavaScript tutorial, you have learned to work with JavaScript variables, arrays and operators.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.