Richland College Multimedia Learning Center

JavaScript, jQuery, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 6/19/2020 at 1:55pm

Data Types and Operators


References


Data Types

A data type is the specific category of information that a variable contains.


Data types that can be assigned only a single value are called primitive types.

The primitive data types in JavaScript are:

Data Type Description
Integers Positive or negative numbers with no decimal places
Floating-point Numbers Positive or negative numbers with decimal places or written using exponential notation
Booleans Logical values of either true or false
Strings Text -- sequences of characters -- such as "Hello world!"
Undefined The value in a variable that has not been assigned a value, or has not been declared, or does not exist
Null An empty value

The null value is a special value that tells JavaScript that the variable does not contain a value, but the variable is not undefined (see below). As weird as that sounds, even though we refer to a null value, JavaScript interprets the null value as "nothing".

An undefined value means that the variable has been declared but has not had a value assigned to it (not even a null value -- see above), or has not been declared (which means that the variable does not exist).


Data types that can be assigned multiple values are called composite types.

The composite data types in JavaScript are:

Data Type Description
Functions Groups of code containing variables and statements
Objects Contain properties, methods, and other objects
Arrays Sets of data represented by a single, indexed variable name. We'll see arrays later in this class.



JavaScript is called a loosely typed programming language. JavaScript does not require you to declare the type of data that your variables will contain. In fact, JavaScript does not allow you to declare the type.

JavaScript has a typeof( ) operator that allows you to check on the type of data that is stored in a variable, if you ever need to know the type. Here is a list of the possible values returned by the typeof( ) operator:

Type of Data Return Value from typeof( )
Integers and floating-point numbers "number"
Text strings "string"
true or false "boolean"
Objects, arrays, and null variables (Feel free to regard this as weird behavior by JavaScript. Why should null be an "Object" type?) "object"
Functions "function"
Undefined variables "undefined"

You use the typeof( ) operator like this:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Use the Typeof Operator</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <script type="text/javascript">
    /* <![CDATA[ */
	function myFunction() {
	  alert("What?");
	}
	
	var myArray = new Array();
    /* ]]> */
  </script>
</head>

<body>
  <div id="mainDiv">
  <script type="text/javascript">
    /* <![CDATA[ */
    var myVar;
    document.write("myVar before being assigned a value has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    myVar = "You gotta love JavaScript!";
    document.write("myVar for a string has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    document.write("typeof typeof is: <span class='attention'>" + typeof(typeof(myVar)) + "</span><br>");
    myVar = 100;
    document.write("myVar for 100 has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    myVar = 3.689;
    document.write("myVar for 3.689 has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    myVar = false;
    document.write("myVar for false has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    document.write("myVar for an array has the type: <span class='attention'>" + typeof(myArray) + "</span><br>");
    myVar = null;
    document.write("myVar for null has the type: <span class='attention'>" + typeof(myVar) + "</span><br>");
    document.write("myVar for a function has the type: <span class='attention'>" + typeof(myFunction) + "</span><br>");
    /* ]]> */
  </script>
  </div>
</body>
</html>

And the code looks like this when it is running.

Please note these points about the above code:


Numeric Data Types

The two numeric data types in JavaScript are integers and floating-point numbers.

Integers are positive or negative numbers with no decimal places, like 34, -234, 0, and 100000.

Floating-point numbers contain decimal places or are written in scientific notation, like 4.5, -6.78, 0.52, .52, 2.5E12, and 2.5e12.


Boolean Values

Boolean values are the logical values of true or false. By the way, the term "boolean" comes from the name of the 19th-century mathematician George Boole, who researched and developed theories of mathematical logic.

Here is some sample code that we saw in the previous handout, which shows how a boolean value can be used. Recall that the confirm( ) built-in method returns true if the user clicks the "OK" button, and false if the user clicks "Cancel":

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Click Event in Anchor Tag</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <script type="text/javascript">
    /* <![CDATA[ */
    function warnUser()
    {
      return confirm("This link is only for people with Golden Retrievers!\n\nClick 'Cancel' if you do not love Golden Retrievers.\n\nClick 'OK' if you love them.");
    }
    /* ]]> */
  </script>
</head>

<body>
  <div id="mainDiv">
	<p>
	<a href="GoldenRetrievers.html" onclick="return warnUser();">Golden Retriever Club Home Page</a>
	</p>
  </div>
</body>
</html>

You can see the above code running in the browser here.


Strings

A text string contains zero or more characters surrounded by double or single quotes. You can use strings as literal values or you can assign them to variables.

A text string must be on a single line in your code. It may possibly display on multiple lines in your text editor, but it must be coded on a single line.

JavaScript has two operators that can be used with strings: + and +=. Both operators are concatenation operators. "Concatenation" is the technical term for combining two strings together to make one longer string.

Here is an example of using a string as a literal value:

  document.write("This is a literal string.");

Here is an example of using a string in a variable:

  var thisString = "This string is in a variable.";
  document.write(thisString);

You can even use an empty string, which is a string that contains zero characters, like this:

  var emptyString = "";
An empty string can be useful if a function or method requires a string argument but you don't want to pass a string that will display. Recall that the prompt( ) method requires two strings as arguments: the first argument is instructions to the user, and the second argument is the initial (default) value that you want to display in the input text box. If you don't want to display any text in the text box, you can pass an empty string literal to the method like this:
  var userName = prompt("Fill in your name", "");

If you need to include a quoted string within another string , you need to use a set of quotes different from the quotes used to delimit the (main) string. If the main string is delimited with double quotes, the included string must be delimited with single quotes, and vice-versa, like this:

  var twoStrings = "This string contains 'another string'."; 

Sometimes you need to put a quote within a string where an embedded set of different quotes is not what you need. For instance, if you have a grammatical possessive within a string that is delimited with single quotes, this code will not work:

  var possessiveString = 'This is my city's zipcode: 75204';
But you can use an escape sequence (see the next section for other escape sequences) to put the possessive apostrophe in the string, like this:
  var possessiveString = 'This is my city\'s zipcode: 75204';

Here is page PossessiveString.html, which contains the previous line of code in it:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Escape Characters</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
</head>

<body>
  <div id="mainDiv">
  <script type="text/javascript">
    /* <![CDATA[ */
    var possessiveString = 'This is my city\'s zipcode: 75204';
    document.write(possessiveString);
    /* ]]> */
  </script>
  </div>
  </body>
</html>

You can see the above code running here.


Escape Sequences

An escape sequence is a special sequence of characters that tells JavaScript that the character following the escape character, which is the backslash, has a special purpose. Some of the JavaScript escape sequences are listed below:

Escape Sequence Character that JavaScript puts in the string
\b Backspace
\f Form feed (tells a printer to eject a sheet of paper)
\n New line
\r Carriage return
\t Horizontal tab
\' Single quotation mark (apostrophe)
\" Double quotation mark
\\ Backslash

Please note that New line and Carriage return characters which are in an HTML page are "eaten" by the browser unless they are contained by the <pre>...</pre> tags.

But when they are in a JavaScript string that is being used for such situations as the display text in an alert( ) window or a confirm( ) window, they are not "eaten". In a situation like this, the New line special character (escape sequence) causes the browser to go down to the next line to continue its display.

Some more code that shows how escape sequences can be used is shown below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Escape Sequences</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
</head>

<body>
  <div id="mainDiv">
	The following text (in the blue box) is contained in a <b><pre>...</pre></b> tag:
	<pre style="background-color:lightblue;">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  document.writeln("This line is displayed \non three lines, since it contains some <b>new line</b> characters\nand is contained by a <b><pre>...</pre></b> tag.");
	  document.writeln("<br/>");
	  document.writeln("This line has a \ttab in it before the word \"tab\".");
	  document.writeln("<br/>");
	  document.writeln("My files are in folder c:\\personalstuff\\");
	  document.writeln("<br/>");
	  document.writeln("My dog's name is \"Noah\".");
	  document.writeln("<br/>");
	  document.writeln('I like my dog\'s name.');
	  /* ]]> */
	</script>
	</pre>

	The following text (in the green box) is <b>not</b> contained in a <b><pre>...</pre></b> tag:<br /><br />
	<p style="background-color:lightgreen;">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  document.writeln("This line is displayed \nas a single line (which may be wrapped by the browser), even though it contains some <b>new line</b> characters,\nbecause it is <b>not</b> contained by a <b><pre>...</pre></b> tag.");
	  document.writeln("<br/>");
	  document.writeln("This line has a \ttab in it before the word \"tab\".");
	  document.writeln("<br/>");
	  document.writeln("My files are in folder c:\\personalstuff\\");
	  document.writeln("<br/>");
	  document.writeln("My dog's name is \"Noah\".");
	  document.writeln("<br/>");
	  document.writeln('I like my dog\'s name.');
	  /* ]]> */
	</script>
	</p>

	<script type="text/javascript">
	  /* <![CDATA[ */
	  function showSomeText()
	  {
		alert("This line is displayed on two lines, since it contains NO new line characters and is displayed by an alert box.");
		alert("This line is displayed \non four lines, since it contains some\nnew line characters\nand is displayed by an alert box.");
	  }
	  /* ]]> */
	</script>

	<a href="#" onclick="showSomeText(); return false;">Show some text in some "alert" boxes.</a>
  </div>
</body>
</html>
You can see the above code running here.


Arrays

We will see Arrays again in a few weeks, when we talk about loops and repetition. For now, note that an Array is a set of data represented by a single, indexed variable name.

Arrays are represented in JavaScript by the Array object, which contains a constructor function named Array( ). As with any other object in JavaScript, you create a new Array object with the new keyword, like this:

  var hospitalDepartments = new Array(10);

You should note that the numeric argument to the Array constructor function tells JavaScript how many items will be in the array. This argument is, however, optional. In JavaScript, you can add items (elements) to the array as needed, and JavaScript will automatically adjust the count of elements in the array.

Each item in an array is called an element.

The numbering of elements within JavaScript arrays starts with index number zero (0). You refer to a specific element of a JavaScript array by giving the array name followed by the index number enclosed in square brackets, like this:

  hospitalDepartments[0] = "Anesthesia";
  hospitalDepartments[1] = "Molecular Biology";
  hospitalDepartments[2] = "Neurology";
  hospitalDepartments[3] = "Oncology";
  hospitalDepartments[4] = "Ophthalmology";
  hospitalDepartments[5] = "Otolaryngology";
  hospitalDepartments[6] = "Pediatrics";
  hospitalDepartments[7] = "Psychiatry";
  hospitalDepartments[8] = "Pulmonary Diseases";
  hospitalDepartments[9] = "Radiology";

Once you have assigned a value to an array element, you can, just as with any other variable in JavaScript, change the value later if needed, like this:

  hospitalDepartments[5] = "Prosthetics";

Most programming languages require that all of the elements in an array contain data of the same data type, but JavaScript does not limit you with this requirement. You can mix different data types in JavaScript arrays if you wish, although this practice is not recommended.

You can assign values to array elements when you first create the array, like this:

  var hospitalDepartments = new Array ("Anesthesia", "Molecular Biology",
    "Neurology");

The Array object contains various methods that we will not discuss here. But a very useful property of the Array object is the length property. The length property contains a value that tells you how many elements are in the array. For instance, you can display how many elements are in an array like this:

  document.write("There are " + hospitalDepartments.length + " departments in this hospital.");

You can use an array almost anywhere that a normal variable can be used. In the following example, an array will be used to put some information into the page with document.write().

  <body>
  <script type="text/javascript">
    /* <![CDATA[ */
    document.write("The third department at the hospital is " + hospitalDepartments[2]  + ".<br />");
    document.write("The tenth department at the hospital is " + hospitalDepartments[9]  + ".<br />");
    document.write("There are " + hospitalDepartments.length + " departments in this hospital.");
    /* ]]> */
  </script>
  <noscript>
    <p>
      Turn on JavaScript!!
    </p>
  </noscript>
  </body>

Associative Arrays

There is another form of array indexing in JavaScript, used with an array type called "Associative Arrays". In an associative array, the index is a string instead of a number.

Here is some code that shows how a string can be used as an array index in JavaScript:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Phone Book Demo</title>
  <link rel="stylesheet" type="text/css" href="Samples.css">
<script type="text/javascript">
    /* <![CDATA[ */
    var phone_book = new Array();
    phone_book["happy"] = "(203) 555-1111";
    phone_book["sleepy"] = "(203) 555-2222";
    phone_book["sneezy"] = "(203) 555-3333";
    phone_book["sleezy"] = "(203) 555-4444";
    phone_book["sneary"] = "(203) 555-5555";
    phone_book["bleary"] = "(203) 555-6666";
    phone_book["tweaked"] = "(203) 555-7777";
    
    function displayNumber(the_phone_book, entry)
    {
    	var the_number = the_phone_book[entry];
    	document.getElementById("number_box").value = the_number;
    }
    /* ]]> */
  </script>
</head>
<body>
	<div id="mainDiv">
		<h1>The Dwarves of Multimedia Gulch</h1>
		<form name="the_form" action="" method="post">
		<table border="0" cellpadding="5" cellspacing="0">
		  <tr>
			<td valign="top"><b>Name:</b></td>
			<td valign="top">
				<select onchange = "displayNumber(phone_book, this.options[this.selectedIndex].value);"
				   size="7">
				<option value="happy">Happy</option>
				<option value="sleepy">Sleepy</option>
				<option value="sneezy">Sneezy</option>
				<option value="sleezy">Sleezy</option>
				<option value="sneary">Sneary</option>
				<option value="bleary">Bleary</option>
				<option value="tweaked">Tweaked</option>
				</select>
			</td>
			<td valign="top"><b>Number:</b></td>
			<td valign="top">
				<input type="text" name="number_box" id="number_box" value="" />
			</td>
		  </tr>
		</table>
		</form>
	</div>
</body>
</html>

You can see the above code running here.

Please note these points about the above code:

Below is a second example of an associative array. You should note carefully in this example that the length property has a value of 0 in an associative array:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Test Associative Arrays</title>
</head>

<body>
  <div id="mainDiv">
    <h3 style="text-align:center;">Testing Associative Arrays</h3>
	<script type="text/javascript">
		/* <![CDATA[ */
		var myArray = new Array();

		myArray["one"] = 100;
		myArray["two"] = -1.35;
		myArray["three"] = "Kangaroo";

		for (stuff in myArray)
		{
		  document.write("The value for index '" + stuff + "' is " + myArray[stuff] + "<br>");
		}

		document.write("The length property has a value of " + myArray.length);
		/* ]]> */
	</script>
  </div>
</body>
</html>
You can see the above code running here.

Please note these points about the above code:


Expressions

A JavaScript expression is a combination of literal values, variables, operators, and other expressions that the JavaScript engine evaluates (interprets and figures out the value of). An expression can be as simple as a literal value, such as

  "this is a string value"  // string literal expression
  10  // integer literal expression
  3.156  // floating-point literal expression
  true  // boolean literal expression
  null  // null literal expression
  employee_number  // variable expression

You can also make complex expressions by combining variables and literals (called operands) with operators. Operators are symbols used in expressions to manipulate the operands.

You have already seen several types of expressions, such as

  myNumber = 100;

where the assignment operator (=) is used.

We will see other types of operators in the next section. For now, note that the types of operators in JavaScript are listed below:

Operator Type Description
Arithmetic Used to do mathematical calculations
Assignment Assigns values to variables
Comparison Compares operands and returns a boolean value
Logical Used for doing boolean operations on boolean operands
String Used for doing operations on strings
Special Used for various purposes. This type includes the conditional, instance of, in, delete, void, new, this, typeof, and comma operators.

JavaScript operators are either unary or binary.

A binary operator requires an operand both before and after the operator. For example, the assignment operator is a binary operator, as in the statement

  myNumber = 100;

A unary operator requires a single operand either before or after the operator. For example, the increment operator (++) increases the value of a numeric variable by 1. It is used like this:

  myNumber++;

Arithmetic Operators

The arithmetic binary operators in JavaScript are listed below:

Arithmetic Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus -- divides two operands and returns the remainder

The arithmetic unary operators in JavaScript are listed below:

Arithmetic Operator Description
++ Increment -- increases the operand by a value of 1
-- Decrement -- decreases the operand by a value of 1
- Negation -- changes the sign of the operand (negative or positive)

[ Optional Section ]

You should note carefully that the increment and decrement operators can be used either as a prefix operator or a postfix operator. Also, you should note carefully that operators do return a value. The difference here is that the prefix operator returns the operand's value after it changes the operand, and the postfix operator returns the operand's value before it changes the value of the operand.

The concept of prefix operators versus postfix operators is shown in the code below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Prefix and Postfix Operators</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  var count = 10;
	  var newValue = ++count;
	  document.write("10 incremented with a prefix operator (++count) returns " + newValue + "<br>");
	  document.write("The incremented value (count) is " + count + "<br><br>");
	  
	  var count2 = 10;
	  var newValue2 = count2++;
	  document.write("10 incremented with a postfix operator (count2++) returns " + newValue2 + "<br>");
	  document.write("The incremented value (count2) is " + count2 + "<br>");
	</script>
  </div>
</body>
</html>

You can see the above code running here.

[ END of Optional Section ]


Assignment Operators

The assignment operators in JavaScript are listed below:

Assignment Operator Description
= Assigns the value of the right operand to the left operand
+= Combines the value of the right operand with the value of the left operand (strings), or adds the value of the right operand to the value of the left operand and assigns the new value to the left operand (numbers)
-= Subtracts the value of the right operand from the value of the left operand and assigns the new value to the left operand
*= Multiplies the value of the right operand by the value of the left operand and assigns the new value to the left operand
/= Divides the value of the left operand by the value of the right operand and assigns the new value to the left operand
%= Divides the value of the left operand by the value of the right operand and assigns the remainder to the left operand

You can use the += operator to combine strings as well as numbers. In the case of strings, the string on the left side of the operator is combined with the string on the right side of the operator, and the new value is assigned to the left operand. The process of combining strings is technically called "concatenation".

If needed, the JavaScript engine will attempt to convert a string operand to a numeric operand. If the engine cannot do so, it will convert the value to NaN, which is a special value that stands for "Not a Number".

Some code that illustrates the use of the assignment operators is below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Assignment Operators</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var x, y;
	  x = "Hello ";
	  x += "world!";
	  document.write(x + "<br>");
	  
	  x = 100;
	  y = 200;
	  x += y;
	  document.write("x += y (x is 100; y is 200) gives " + x + "<br>");
	  
	  x = 10;
	  y = 7;
	  x -= y;
	  document.write("x -= y (x is 10; y is 7) gives " + x + "<br>");
	  
	  x = 2;
	  y = 6;
	  x *= y;
	  document.write("x *= y (x is 2; y is 6) gives " + x + "<br>");
	  
	  x = 24;
	  y = 3;
	  x /= y;
	  document.write("x /= y (x is 24; y is 3) gives " + x + "<br>");
	  
	  x = 3;
	  y = 2;
	  x %= y;
	  document.write("x %= y (x is 3; y is 2) gives " + x + "<br>");
	  
	  x = "100";
	  y = 5;
	  x *= y;
	  document.write("x *= y (x is \"100\"; y is 5) gives " + x + "<br>");
	  
	  x = "one hundred";
	  y = 5;
	  x *= y;
	  document.write("x *= y (x is \"one hundred\"; y is 5) gives " + x + "<br>");
	  /* ]]> */
	</script>
  </div>
</body>
</html>
You can see the above code running here.


Comparison Operators

The JavaScript comparison operators are listed below:

Comparison Operator Description
== Equal - returns true if the operands are equal
=== Strict equal - returns true if the the operands are equal and are of the same type
!= Not equal - returns true if the operands are not equal
!== Strict not equal - returns true if the operands are not equal or are not of the same type
> Greater than - returns true if the left operand is greater than the right operand
< Less than - returns true if the left operand is less than the right operand
>= Greater than or equal - returns true if the left operand is greater than or equal to the right operand
<= Less than or equal - returns true if the left operand is less than or equal to the right operand
?: Conditional - executes one of two expressions, based on the results of a conditional expression. (See the next section.)

You should note that you can use either string or numeric operands with the comparison operators.

A numeric comparison is straightforward.

A string comparison is done in alphabetical order.

When one operand is a string and the other is a number, JavaScript attempts to convert the string value to a number and to do a numeric comparison. If the string value cannot be converted to a number, a value of false is always returned.

Some code that shows how the comparison operators work is shown below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Comparison Operators</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var x = 5;
	  var y = 6;
	  document.write("x is 5, and y is 6<br>");
	  document.write("x == y gives " + (x == y) + "<br>");
	  document.write("x != y gives " + (x != y) + "<br>");
	  document.write("x > y gives " + (x > y) + "<br>");
	  document.write("x < y gives " + (x < y) + "<br>");
	  document.write("x >= y gives " + (x >= y) + "<br>");
	  document.write("x <= y gives " + (x <= y) + "<br><br>");
	  
	  x = "a string";
	  y = "a different string";
	  document.write("x is \"a string\", and y is \"a different string\"<br>");
	  document.write("x == y gives " + (x == y) + "<br>");
	  document.write("x != y gives " + (x != y) + "<br><br>");
	  
	  x = "abc";
	  y = "ABC";
	  document.write("x is \"abc\", and y is \"ABC\"<br>");
	  document.write("x == y gives " + (x == y) + "<br>");
	  document.write("x != y gives " + (x != y) + "<br><br>");
	  
	  x = 5;
	  y = "5";
	  document.write("x is 5, and y is \"5\"<br>");
	  document.write("x == y gives " + (x == y) + "<br>");
	  document.write("x === y gives " + (x === y) + "<br>");
	  document.write("x != y gives " + (x != y) + "<br>");
	  document.write("x !== y gives " + (x !== y) + "<br><br>");
	  /* ]]> */
	</script>
  </div>
</body>
</html>
You can see the above code running here.


[ Optional Section ]

The Conditional Operator

The conditional operator has this syntax:

  conditional expression ? expression1 : expression2;

(We will look at the conditional operator in more detail in the handout "Decision Making".)

If the conditional expression evaluates to true, expression1 is executed. If the conditional expression evaluates to false, expression2 is executed.

An example of a conditional operator expression is shown below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <title>Conditional Expression</title>
  <script type="text/javascript">
    function checkTheNumber()
    {
      var yourNumber = document.getElementById("yourNumber").value;
      var intVariable = 150;
      var result;
    
      (yourNumber > 100) ? result = "greater than" : result = "less than or equal to";
      document.getElementById("compareText").innerText = result;
      document.getElementById("mainDiv").style.visibility = "visible";
    }
  </script>
</head>

<body>
<div id="mainDiv" style="visibility:hidden;">
  Your number is <span id="compareText"></span> 100.
</div>
<br />
<form action="" method="post">
  <input type="text" id="yourNumber" />
  <br />
  <br />
  <input type="button" value="Test the number" onclick="checkTheNumber()" />
</form>
</body>
</html>

and this code can be seen running here.

[ END of Optional Section ]


Logical Operators

The JavaScript logical operators are listed below:

Logical Operator Description
&& And - returns true if both the left operand and right operand return a value of true; otherwise, it returns false
|| Or - returns true if either the left operand or right operand returns a value of true. If both the left and right operands return a value of false, this operator returns false.
! Not - returns true if an expression is false, and returns false if an expression is true

The && and || operators are binary operators. The ! operator is a unary operator.

The following two tables should help you understand under what conditions the logical operators return true or false:

If Condition 1 is and Condition 2 is the result of Condition 1 AND Condition 2 is
true true true
true false false
false true false
false false false

If Condition 1 is and Condition 2 is the result of Condition 1 OR Condition 2 is
true true true
true false true
false true true
false false false

Some code that illustrates the use of logical operators is shown below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Logical Operators</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var x = 5;
	  var y = 6;
	  
	  var result = (x > y) && (y == 6);
	  document.write("x is 5 and y is 6 <br>");
	  document.write("(x > y) && (y == 6) gives " + result + "<br>");
	  
	  result = (x < y) && (y == 6);
	  document.write("(x < y) && (y == 6) gives " + result + "<br>");
	  
	  result = (x > y) || (y == 6);
	  document.write("(x > y) || (y == 6) gives " + result + "<br>");
	  
	  result = (x > y) || (y > 10);
	  document.write("(x > y) || (y > 10) gives " + result + "<br>");
	  /* ]]> */
	</script>
  </div>
</body>
</html>
You can see the above code running here.


String Operators

JavaScript has two operators that can be used with strings. Both operators are concatenation operators.

String Operator Description
+ Combines two strings. The resulting combined string is usually assigned to a variable.
+= Combines the right string with the left string variable, and assigns the new combined string to the left string variable.

Here is an example:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Concatenation</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var firstString = "Ernest Hemingway wrote ";
	  var secondString = "<em>For Whom the Bell Tolls</em>";
	  var newString = firstString + secondString;
	  document.write(newString);
	  document.write("<br>");
	  
	  firstString += secondString;
	  document.write(firstString);
	  /* ]]> */
	</script>
  </div>
</body>
</html>

You can see the above code running here.

We will see this next feature of JavaScript again later in the semester, but for now I want to show you how JavaScript handles the addition of strings and numbers. In most programming languages you can't add strings and numbers. But if you add a string to a number in JavaScript, JavaScript automatically converts the number into a string, and then concatenates the strings.

Here is page addStringAndNumber.html, which shows how this feature of JavaScript works:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Adding Strings and Numbers</title>
</head>

<body>
  <div id="mainDiv">
  <script type="text/javascript">
  /* <![CDATA[ */
  var theString1 = "We saw ";
  var theString2 = " tigers at the zoo.";
  var theString3 = " lions at the zoo.";
  var theString4 = " large cats at the zoo.";
  var numTigers = 14;
  var numLions = 3;

  var newString = theString1 + numTigers + theString2;
  document.write(newString);

  document.write("<br>");

  newString = theString1 + numLions + theString3;
  console.log("numTigers is " + numTigers);
  console.log(newString);
  document.write(newString);

  document.write("<br>");

  newString = theString1 + numTigers + numLions + theString4;
  document.write(newString);
  /* ]]> */
  </script>

  <h3>That's not right!  Let's try that again....</h3>

  <script type="text/javascript">
  /* <![CDATA[ */
  newString = theString1 + (numTigers + numLions) + theString4;
  document.write(newString);

  document.write("<br>");
  
  var totalCats = numTigers + numLions;
  newString = theString1 + totalCats + theString4;
  document.write(newString);
  /* ]]> */
  </script>
  </div>
</body>
</html>

You can see the above code running here.

Please note these points about the above code:


The String Object

All literal strings and string variables in JavaScript are represented by the String object, even though you can usually use the strings and variables without being aware of the String object that you are dealing with. But if you need them, the String object contains many useful methods for manipulating the text string. Here is a list of some of these String object methods:

String object method Description
charAt(index) Returns the character at the specified position (index) in the text string. Returns nothing if the specified position (index) is greater than the length of the text string.
indexOf(text, index) Returns the position number in a text string of the first character of the text argument. If the index argument is included, indexOf( ) starts searching at that position in the text string. Returns -1 if the text is not found.
lastIndexOf(text, index) Returns the position number in a text string of the last instance of the first character of the text argument. If the index argument is included, lastIndexOf( ) starts searching at that position in the text string. Returns -1 if the text is not found.
split(separator) Divides a text string into an array of substrings, separating the pieces at the specified separator character.
substring(starting index, ending index) Extracts text from a string starting with the position number in the string given by the starting index argument, and ending with the position number in the string given by the ending index argument.
toLowerCase( ) Converts the text string to lower-case characters.
toUpperCase( ) Converts the text string to upper-case characters.

You should note carefully that the index numbers in strings start with zero (0), not 1.

You should also note that the String object contains a property called length which has the value of the number of characters in the string.

Some code that illustrates how these String object methods and the length property are used is shown below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>String Methods</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var myString;
	  var myPos;
	  var myLength;
	  
	  myString = "JavaScript".charAt(5);
	  document.write("charAt(5) in \"JavaScript\" is " + myString + "<br>");
	  myPos = "JavaScript".indexOf("S");
	  document.write("indexOf(\"S\") in \"JavaScript\" is " + myPos + "<br>");
	  myPos = "JavaScript".indexOf("s");
	  document.write("indexOf(\"s\") in \"JavaScript\" is " + myPos + "<br>");
	  myPos = "JavaScript".lastIndexOf("a");
	  document.write("lastIndexOf(\"a\") in \"JavaScript\" is " + myPos + "<br>");
	  myString = "JavaScript".toUpperCase();
	  document.write("\"JavaScript\".toUpperCase() is " + myString + "<br>");
	  myString = "JavaScript".toLowerCase();
	  document.write("\"JavaScript\".toLowerCase() is " + myString + "<br>");
	  myLength = "JavaScript".length;
	  document.write("\"JavaScript\".length is " + myLength + "<br>");
	  /* ]]> */
	</script>
  </div>
</body>
</html>

You can see the above code running here.

[ Optional Section ]

One of the real-world things you can do with the String object methods is to make sure the user has given you a valid e-mail address. Here is a page, emailValidation.html, that validates an e-mail address:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Validating an Email Address</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <script type="text/javascript">
    /* <![CDATA[ */
    function checkEmail(the_email)
    {
        var the_at = the_email.indexOf("@");
        var the_dot = the_email.lastIndexOf(".");
        var a_space = the_email.indexOf(" ");
        if ((the_at != -1) &&  // if there's an '@'
            (the_at != 0) &&  // and it's not at position 0
            (the_dot != -1) && // and there's a '.'
            (the_dot > the_at + 1) &&  // and something between the '@' and '.'
            (the_dot < the_email.length - 1) && // and something after the '.'
            (a_space  == -1) &&  // and there're no spaces
            (!hasIllegalCharacters(the_email,'!#$%^&*')))  // and no illegal chars
         {
                 alert("Your e-mail address appears to be valid!");
                 return true;
         }  
         else if (the_at == -1)
         {
                 alert("You need an @ sign in the address.");
                 return false;
         }
         else if (the_at == 0)
         {
                 alert("The @ sign cannot be the first character.");
                 return false;
         }
         else if (the_dot == -1)
         {
                 alert("You need a server designator such as \".com\" or \".org\" or \".edu\" etc.");
                 return false;
         }
         else if (the_dot == the_email.length - 1)
         {
                 alert("The period cannot be the last character.");
                 return false;
         }
         else if (a_space != -1)
         {
                 alert("You have one or more spaces -- remove them, please.");
                 return false;
         }
         else if (hasIllegalCharacters(the_email,'!#$%^&*'))
         {
                 alert("You cannot use the characters ! # $ % ^ & *.");
                 return false;
         }
         else
         {
                 alert("Sorry, your email address appears to be invalid!");
                 return false;
         }
    }
    
    function hasIllegalCharacters(test_string, illegal_string)
    {
        var is_illegal = false;
        var the_char = "";
        for (var loop=0; loop < illegal_string.length; loop++)
        {
            the_char = illegal_string.charAt(loop);
            if (test_string.indexOf(the_char) != -1)
            {
                is_illegal = true;
            }
        }
        return is_illegal;
    }
    /* ]]> */
  </script>
</head>
<body>
  <form method="post" action="" 
        onsubmit="var result = checkEmail(this.emailbox.value); return false;">
     E-mail Address: <input type="text" name="emailbox" />
     <br />
     <input type="submit" value="Give me your e-mail address!" />
  </form>
</body>
</html>

You can see the above page running here. Please note the use of the indexOf( ) and lastIndexOf( ) methods. Also please note that there is a better way to validate e-mail addresses, which we will see in the handout "Regular Expressions".

[ END of Optional Section ]


Operator Precedence

When you combine operators in JavaScript expressions, the JavaScript engine evaluates the operators in an order determined by the priority of the operators. Rather than confuse you with the list of operator precedence given in the book, let me give you Link's Rule for dealing with operator precedence:

Always use parentheses to force the browser to evaluate the operators in the order that you want.
This rule is based on the fact that parentheses have the highest precedence, so you can use parentheses to override any other precedence that the JavaScript engine might try to enforce. Remember: You are the programmer, and you are in charge!

An example of what this rule means is given below:

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="Samples.css">
  <title>Precedence</title>
</head>

<body>
  <div id="mainDiv">
	<script type="text/javascript">
	  /* <![CDATA[ */
	  var firstResult = (5 + 2) * 8;
	  var secondResult = 5 + (2 * 8);
	  var thirdResult = 5 + 2 * 8;
	  document.write("(5 + 2) * 8 is " + firstResult + "<br>");
	  document.write("5 + (2 * 8) is " + secondResult + "<br>");
	  document.write("5 + 2 * 8 is " + thirdResult + "<br>");
	  /* ]]> */
	</script>
  </div>
</body>
</html>
The point of this sample is that you can make the JavaScript engine evaluate operands in the order that you want. And you can see the above code running here.


[ Optional Section ]

A Calculator and eval()

You should now know enough to understand the calculator program that we looked at in the first handout. But first you need to know how the eval( ) built-in method works.

The eval( ) method evaluates expressions contained within strings. This means that you can construct a JavaScript statement in a string, and then use eval( ) to execute the statement that is in the string. The one restriction that JavaScript places on this way of running statements is that you must make sure that the string that you pass to the eval( ) method contains operators and/or numbers. Please note that the concatenation operator does qualify, so your string can contain expressions that add strings.

This calculator (with parentheses that I added) can be seen running here. View the source by right-clicking in the frame after the program loads.

[ END of Optional Section ]