Lesson # 6 - Data Types and Operators

# 6 - Data Types and Operators

# 6 Review Questions # 6 Assignment

Recall that in JavaScript, the variables don't have any specific data type, which is quite different from some of the other popular languages. Rather, the values that are assigned to the variable has a specific type. The type of the data determines what you can do with that data. Imagine trying to multiply your first name by 400. Makes no sense to us or to the computer. That's because your name is string data, which is not geared toward doing math. Also, think about converting the number 123 to upper case. Since there is no such thing as upper and lower case numbers, that also makes no sense. We like numbers to be able to perform all the math we need, and strings need to be manipulated in other ways.

Here is a chart of the basic data types that we will be using in these JavaScript lessons.

Value DataType What it can store Examples
int
positive and negative whole numbers between -2^53 to +2^53 meaning from -9007199254740992 to +9007199254740992 0,1,2,3,-75, 32677, -30000, 25000000000 but not 3.14 or -25.5
float

floating point decimals in either decimal format or scientific notation between approximately + or - 1.7976931348623157 x 10^308 down to  + or - 5 x 10 ^ -324

3.14159, -900234.2345, and in scientific notation (also known as exponential notation) 7.123 x 10^-22 , -2.07e17 (where 'e' means 10 raised to the power of 17)
Boolean
These are nifty ways to hold true or false values, with false being considered a 0 and true is non-zero. Useful for testing for certain logical conditions. This type is named after George Boole, a famous mathematician. true, false but not maybe.
String
Any kind of text including letters, numbers, punctuation characters that probably won't be used for doing math. Examples are people's names, merchandise items for sale on e-bay, addresses, zip codes, social-security numbers, telephone numbers, the words to a song, etc.Strings need to be enclosed in single or double quotation marks. Note that information entered into an input field will always be stored as string, so if we need to perform mathematics on numberical data, we need to change it to a number first. This is covered late in this lesson. "Good evening", "Arnold Schwartzenegger", "503-431-4000", "97223", "mypassw0rd"
Null
Completely devoid of any value null
Object
All properties and all methods belonging to that object or Array.  
Function
A function definition  

String Operators

We know that strings are sets of characters enclosed in quotation marks, such as "Arnold Schwartzenegger" and "1-800-257-7272". (That's my favorite Pizza place.) And there are just two operators that we use with strings, + and +=.

+ The plus + sign takes two strings and concatenates them, meaning it attaches them together to form one string. We can use this resulting string in a couple of different ways. We can send it to be output as in

alert( " Hello " + firstName); //where firstName is a variable containing "Bob"

Or we can assign it to a variable to be stored for later use as in

var fullName = firstName + " " + midInitial + ". " + lastName;

+= The plus-equals += is a combination of concatenation and assignment. Therefore it can only be used with a variable name on the lhs ( that's short for left hand side) of the equal sign. The rhs (you could guess that this means right hand side) can either be a variable or a string literal enclosed in quotes. For example:

fullName = "Mr. ";
fullName += "Bob Dobolino";      // note that fullName now contains 'Mr. Bob Dobolino', which is fun to say      three times fast.

 

String Functions - AKA String Methods

There are a ton of methods in JavaScript to help us work with strings, too many to cope with all at once. But you can see a complete list of string functions or methods, click on complete list of string functions. The reference is on Netscape's web site at

http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm.

We will see some examples of how a few of the most useful ones work here. To use a string method, we use the dot notation and the name of the string object to reference the method. For example, if we want to make fullName into all upper case letters, it looks like these two examples:

var fullNameCaps = fullName.toUpperCase();  //since the method toUpperCase returns a value, we need to put that value somewhere
alert(fullName.toUpperCase() );

Please be careful with the EXACT spelling, including any capital letters, in the method names. indexOf() and indexof() are not the same thing in JavaScript. Also note that names of methods always use parentheses. Some methods, such as alert(), require that some value (the argument) be included inside the parentheses, and others do not require any argument. I always try to stay out of arguments, myself, but sometimes you have to get involved, right?

You can use the string.indexOf() method to have your program find out if one string is contained inside another. Strings have an index, which means the position of a character inside a string, starting at 0. So study this little sample and the comments:

var pigLatin = "avaScriptJay";
var location= pigLatin.indexOf("s");      // location evaluates to '-1' meaning no such position - no lower case 's' in that string
location = pigLatin.indexOf("S");      // location is now 3, since counting starts at 0 and 'S' is in the fourth  position
location = pigLatin.indexOf("Jay");      // location is now 9, since the smaller string 'Jay' starts in the 10th position.

string.length is used to determine the length of a string in characters. It counts every character, including spaces and punctuation marks. so

var count=pigLatin.length evaluates to 12 and "My O My!".length evaluates to 8.

Another useful one is the string.substring() method, which will extract a smaller string from within a larger string. Suppose we have a string that contains the name "Arnold Schwartzenegger" and we want to extract the last initial only. We know that the initial will occur just after the first space so we can use indexOf() to find the space, then use substring() to get the character after the space.

fullName = "Arnold      Schwartzenegger";
var spaceLocation = fullName.indexOf("      "); // find the space - here it has index 5
var lastInitial = fullName.substring(spaceLocation      + 1, 1); // looks in position 6 and grabs one character to return
alert(" The last initial      is " + lastInitial);

Converting Strings to Numbers is needed whenever we use text boxes to get information from a user. The value property of an <INPUT TYPE="text"> is always string, so doing math is not possible until we convert the string to its numeric version. There are two methods, parseInt() and parseFloat() that will take a string of text and convert it to its number form. "Parse" is a programming term that basically means to evaluate some string of text in a character-by-character fashion and try to make some sense out of it, which is different from parseley which, when evaluated, tastes too much like rabbit food.

The syntax of parseInt() is:

parseInt(str [, radix])

parseInt() takes its first argument, the string 'str', and attempts to convert it to an integer, and return that integer. The optional part '[radix]' allows us to get really fancy and tell JavaScript what number base we want. If you leave it out, you get good old-fashioned decimal, or base ten integers. For example, a radix of 8 indicates that you want to convert to a base eight or octal number,and radix of 16 means hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.

parseFloat() works the same as parseInt(), except that it has the ability to convert to a decimal value

Examples: Here is how they are used:

var someDecimal = parseInt("12345"); // means convert this string to the whole number 12345.

var someDecimal = parseInt(stringOfNumbers, 10); // the 10 means decimal, or base 10. OK to leave it off.

var someBinary = parseInt("00100",2); // returns the binary integer 100

var someHex = parseInt("G00D", 16); // returns the hex number G00D. Note that G, 0, D are all legal digits in hex

var ageInYears = parseInt(form.inputAge.value); //this takes an age that the user entered and converts it from string to integer

var salePrice = parseFloat(form.inputRegPrice.value) * .75; // This calculates a sale price of 25% off -it converts regular Price to a float then does the math

** Note that if either method finds a character that it doesn't recognize as a digit in that number base, then it quits converting and skips any remaining characters. If the first character can't be converted, it returns the value 'NaN', meaning "Not a Number'.

There is another global function called Number() that will also do the job of converting a string to a number. Here is how it is used:

var a = "123"; // a is a string
var b = Number(a); // b is now the number 123

 

Math Operators

JavaScript uses the usual basic 4 math operators + - * / just as you would think. There are a few more math operators that should be explained. The modulus operator % is used to perform a division, then return just the remainder. So 8 % 5 is 3, and 5 % 2 is 1. One common use for this is to check whether a number is even or odd, since all even numbers n % 2 would result in 0, and all odd numbers n % 2 would equal 1.

There are also the arithmetic assignment operators that are the same as the operators in C++ or Java. They take whatever variable is on the left hand side, do the math with the amount on the right hand side, and then store the result back into the variable on the left.

var a = 10;
a +=5; // this means a = a + 5, so now a is 15
a *=2;  // this means a = a * 10 so now a is 20
a -=8;  //this means a = a - 8 so now a is 2
a %=2; //this means a = a % 2 so now a is zero since 12 was even

There are also the increment ++ and decrement -- operators, that either add 1 or subtract 1 to the variable that precedes them. We use ++ as a counting method to bump a variable up by 1 each time as in counter++, and of course we could count backwards by doing counter--; ( These statements mean counter = counter + 1; and counter = counter - 1;)

Operator Precedence AKA 'Please Excuse My Dear Aunt Sally' Rule

Operator Precedence is the priority of operations that JavaScript will use to decide what to do first whenever we perform multiple calculations in the same statement. Part of these rules are the same one you learned in beginning Algebra class.

The 'Please Excuse My Dear Aunt Sally' rule, is a memory device for remembering the rule'Parentheses, Exponenats, Multiplication and Division, Addition and Subtraction.

Here is the complete list in order of precedence for JavaScript operators. You can make up your own memory device for these, or use mine.

  1. Parentheses, brackets, or dot ( () [] . )
  2. Negation or increment ( ! ++ -- typeof void )
  3. Multiplication, Division, Modulus ( *, / ,% ) left to right
  4. Addition, Subtraction ( + - )
  5. Comparisons ( < > <= >= )
  6. Equals ( == !=)
  7. Logical AND ( && )
  8. Logical OR ( || )
  9. Assignment Operators ( =, +=, -=, *=, /=, %= )

"Parents Never Make Dessert Mine, And Summer Comes Every Afternoon On Aruba" ... told you to make up your own, right?

Examples:

5+3*8 evaluates to 29 because we multiply 3*8 first then add 5 + 24

( 5 + 3 ) * 8 evaluates to 64 because we add 5 + 3 first, then multiply 8 * 8 to get 64

3 + 5 % 2 evaluates to 4 because 5 % 2 yields a remainder of 1 and 1 + 3 is 4

If in doubt - use parentheses ( ) to ensure your math results will be correctly evaluated.

Math Functions

JavaScript has lots of math functions that are under a global object called Math, with a capital 'M'. The reference to all the features available is on the Netscape web site http://developer.netscape.com/docs/manuals/js/client/jsguide/index.htm.

A word of warning about doing extended mega math - meaning crunching numbers that go out past 15 digits of accuracy. There is a combined task force of the browser that your user will be using to view your web page, and the underlying operating system of the PC or other computer. You will notice some slight differences in math results in doing certain float operations. The point is that for most things, the math ability of JavaScript is more than acceptable. But for anything requiring a very high degree of precision, you may want to choose a more robust application.

The Math Object has several built-in constants that are nice to have. We use them by using the name of the global Math object (note the capital 'M' again) and the dot notation, as in Math.PI and Math.SQRT2. There is even a Math.E for you calculus buffs out there. Notice that all the constants names are in all capital letters.

There are also some math methods to have all sorts of fun with. To name just a few we have Math.abs(value), Math.sin(value), Math.tan(value), and Math.log(value). Check the website reference above to see the details of those.

Want to have some fun with the math available in JavaScript? Let's play some dice! A specific method that we can have some fun with is Math.random() that returns a random decimal between 0 and one. By itself it is not that useful, but we can tweak it a bit by also using the Math.floor() method that returns the value rounded down to the nearest whole integer. The formula for generating any random integer between 0 and some top value is

var randomInt = Math.floor(Math.random() * top);

where top is the end of the range of values we need. For dice, we need the values to start at 1, since you can't roll a 0 on die, so we need to add the start value which is one. Since the range is 6, we multiply by 6 and then add 1.

Here is how it looks in code:

var die1 = Math.floor(Math.random() * 6) +1; // some integer from 1 to 6

// Now create die2 and we could play a little casino game - Lay down your bet!

Troubleshooting
When using JavaScript, or any programming language to perform math or text operations, you have full responsibility for the correctness of the output. You need to double check that certain inputs will not embarrass you by crashing your program. For numbers, the things to watch for are
  1. Division by zero error - crashes every time. Check the variable or the expression to make sure it is non-zero before you actually perform the division.
  2. Square root of a negative error - just as bad as #1. Before using the Math.sqrt() method, make sure your value is non-negative.
  3. Overflow error - when the size of the value exceeds the capacity of the variable that you assign it to, bad output or a program crash!
  4. NaN - means na-na-na - stands for Not a Number. This will occur when you and your program are both mixed up about data types.

Return to Top of Page | Back to Main Menu