Javascript Basics Part 5

By Mark Kahn

This is the fifth article in a series that will introduce you to the JavaScript language. Up until now we have been focusing on the language constructs of JavaScript: if statements, loops, functions, etc. In this primer we are going to take a step back and cover the inner workings of some of the native JavaScript objects: Strings, Numbers and Arrays.

Strings

As you already know, a string is any snippet of text in JavaScript. As with many other things in JavaScript, there are several different ways to define a string:

var myString = 'Hello, World!';
var myString = new String('Hello, World!');
The first method is what you will probably always use. The second method is rarely used and is only really useful to guarantee that what you are getting is a string. For example:
var n = 5;
var s = new String(n*20);
In this example, s will be the string "100". If you simply set s to n*20, s would contain the number 100. Since JavaScript is a weakly typed language, however, this distinction will very rarely have any effect on anything you do.

String Objects (var n = new String('Hello World')) are technically slower with certain operations than String Literals (var n = 'Hello World') in Internet Explorer. This behaviour is reversed in other browsers, however. In any browser, the difference is rarely large enough to warrant putting effort into making the distinction.

The one important distinction is that eval() does not work on a String Object.

What if you have an apostrophe in your string? Well the following code will break:

var n = 'The dog took it's bone outside';
You will notice that the apostrophe in "it's" ends the string. So you are left with the string "The dog took it" followed by "s bone outside'". Well "s bone outside" by itself is not valid JavaScript code (or correct grammar, for that matter), so we get an error. There are two things we can do here. Since we can define a string with either single or double quotes, we could define this string with double quotes. The other option is to escape our apostrophe. To escape something, you simply prefix it with the \ character. The \ character in this context tells your JavaScript that the next character should be taken exactly as it is, and not as a special character.
var n = "The dog took it's bone outside";
var n = 'The dog took it\'s bone outside';
If you need to have a \ in your string, you will escape it the same way: '\\'.

You've seen in a previous article what indexOf and lastIndexOf do. As a refresher, indexOf returns a number containing the first position of one string in another. If the string you are searching for does not exist, indexOf returns -1. lastIndexOf is identical to indexOf except instead of returning the first occurance of a string, it returns the position of the last occurance of a string.

The fact that indexOf and lastIndexOf return -1 if the string does not exist is very useful and allow this function to be use to test if one string exists in another string, a very common task.

There are a few other useful string functions that we will mention and briefly explain.

charAt() tells you what character is at a certain position in the string. So 'Test'.charAt(1) = 'e'.

length tells you the length of a string. 'Test'.length = 4.

substring() gives a string between two indexes. 'Test'.substring(1, 2) = 'e'.

substr() is similiar to substring() except that insted of the second number being an index it is the length of the string you want returned. If this number goes beyond the end of the string, substr() will return the remaining portion of the string. 'Test'.substr(1, 2) = 'es';

toLowerCase() and toUpperCase() do exactly what they sound like: convert a string to lower case or upper case respectively. 'Test'.toUpperCase() = 'TEST';

Examples of all the above functions:

alert('This is a Test'.indexOf('T'));     //  0
alert('This is a Test'.lastIndexOf('T')); //  10
alert('This is a Test'.charAt(5));        //  i
alert('This is a Test'.length);           //  14
alert('This is a Test'.substring(5, 9));  //  is a
alert('This is a Test'.substr(5, 9));     //  is a Test
alert('This is a Test'.toUpperCase());    //  THIS IS A TEST
alert('This is a Test'.toLowerCase());    //  this is a test
The final String function we will show is eval(). eval() takes in a string and executes the string as if it were JavaScript code.
eval("alert('Hello, World!')");
In this example you will get an alert that says "Hello, World!" just as you would if you wrote the alert normally. This is very useful because it allows us to build a string containing code and then execute it.
Numbers
Working with numbers is fairly straight forward in JavaScript. In Article #1 and Article #2 you saw how to do basic arithmetic, the ++, -- operators as well as *=, +=, /= and -=. You also learned that NaN meant "Not a Number" and what the isNaN() function did. By now you know all the basics, but there are still a few things left and a few things to look out for.

The Math object in JavaScript contains functions to do just about anything you would want to do with a number beyond basic arithmetic. Math.PI for example simply contains the number 3.141592653589793. There are functions here for trig (sin, cos, tan, etc), functions for rounding numbers (Math.floor returns a number rounded down, Math.ceil returns a number rounded up, and Math.round rounds a number "normally"), and many others. Since there are so many functions, we're not going to take the time to explain them all here, but instead will just point you to an excellent reference at DevGuru.

Two of the most common tasks dealing with numbers are converting a number to or from a string. We previously stated that JavaScript was weakly typed, meaning that types to not matter, but there are some cases where you want to be certain that you have a number or a string. If you are adding 5 to a number that came from user input, for example, you want to be sure that you have a number and not the word "Hello".

var n = parseInt("3.14"); // 3
var n = parseFloat("3.14") // 3.14
parseInt is a function that returns the integer value of whatever you pass it. "3.14", "3", "3.00001" and "3.9999" all return the value 3. parseFloat, on the other hand, also returns any decimal value. Both of these functions attempt to "clense" the data before returning a number. For example parseInt("3a") will return a value of 3.

There are also several methods you can use whenever you need to convert a number to a string:

var n = 5;

var m = n.toString();
var m = n+'';
var m = new String(n);
As stated earlier, the last method can be a bit quirky, so it is suggested that you stay away from it unless you need to use a String object for a specific reason. The prefered method here is "n.toString()", but it should be noted that the 2nd method is often used. For example if you have an alert, alert('There are currently ' + apples + ' apples'), the number apples is automatically converted into a strong.

If you need to do any string operation on a variable, you must be certain that you have a string. If, for example, you have a 4 digit year and you want to convert it to 2 digits:

var year = 2000;

var sYear = year.toString();
var year2 = year.substr(year.length-2);
You could just as easily subtract 2000 from this date, but what if the date is 1995? or 1800? or 2700 or just 5? You would end up with some very wrong dates if you subtracted 2000 from each of these. With our method you will always end up with a 2 digit year.
Arrays
An array is basically just a list of items. Each item in an array can be whatever you want, but they are usually related to one-another. If, for example, you wanted to keep track of 30 students in a classroom, you could make an array of students:
var students = new Array();

students[0] = 'Sam';
students[1] = 'Joe';
students[2] = 'Sue';
students[3] = 'Beth';
As you can see, defining an array is fairly simple, as are assigning each of its elements. The above example is a lot of code, however, for relatively little output. It should not surprise you by now to discover that there are multiple methods to create an array. A much more compact example would be:
var students = ['Sam', 'Joe', 'Sue', 'Beth'];
This creates exactly the same array as the previous example but as you can see it is much more compact and not any harder to read. The brackets ([ and ]) in this example tell your code that you want to create an array. Simply writing "var students = [];" is the same as writing "var students = new Array();". Some people find that writing out the word "Array" is more obvious than writing "[]", so use whichever method you prefer.

Now what can we do with our array of students? Well, to access any one item in the array you need to know its index. In our first example you'll notice that there are numbers (0-3) in the brackets. These are our indexes. If you want to know the name of the third student you would write "alert(students[2]);". Why 2 and not 3? Arrays in JavaScript are 0-based, meaning that they start at 0 instead of 1. So the first item in our array is students[0], the 2nd item is students[1], the 100th is students[99], etc. There isn't any valid reason behind this (as far as I am aware), it's just how JavaScript and many other languages are. Some other languages use 1-based arrays and objects (Visual Basic sometimes does this).

The most common thing you will do to an array, other than changing its data, is to check how long it is, usually so that we can loop through the array and perform some task on each item.

var students = ['Sam', 'Joe', 'Sue', 'Beth'];
var suffixes = ['1st', '2nd', '3rd', '4th'];

for(var i=0; i<students.length; i++){
	alert('The '+suffixes[i]+' student is '+students[i]);
}

An important thing to note about arrays is that each item can contain any other item. In these examples each item in the array has been a String, but they can also be numbers, objects, functions, even other arrays. A spreadsheet (like Excel) is a very common example of an array containing other arrays. First you would have an array of columns. Each column would then in turn have an array of rows inside of it. We create our array exactly the same way we created our students array:

var spreadsheet = [
	['A1', 'B1', 'C1', 'D1'],
	['A2', 'B2', 'C2', 'D2'],
	['A3', 'B3', 'C3', 'D3'],
	['A4', 'B4', 'C4', 'D4']
];
Line breaks in JavaScript aren't usually important. In this example we use line breaks to make the code more readable and it doesn't effect the code in any way.

You should notice that we have 5 arrays here. The four inner arrays (or nested arrays) are contained by one larger array, spreadsheet. If we want to know the value of the 2nd column, 3rd row we would write:

var col2 = spreadsheet[1];
alert(col2[2]);

// or

alert(spreadsheet[1][2]);
Both of these do the same thing which is to alert "C2".

Moving on, there are a few common tasks that we perform on arrays. The first is adding an item to the end of the array. Going back to our students array, we currently have 4 items. All you have to do to add a new item is to give a value to the 5th item:

var students = ['Sam', 'Joe', 'Sue', 'Beth'];

students[4]               = 'Mike';
students[students.length] = 'Sarah';
students.push('Steve');

// we now have an array with 7 elements: ['Sam', 'Joe', 'Sue', 'Beth', 'Mike', 'Sarah', 'Steve']
Once again there are many ways to do exactly the same thing. The first method, "students[4]" is rarely used because we usually won't know ahead of time exactly how many items we will have. So we use one of the next two methods. "push" is a function that simply adds whatever you give it to the end of an array, as does the method before that.

It's not as common a task, but sometimes we also need to remove an item from an array. Now comes in the "splice" function. Splice is a very dynamic function and can be used to add or remove as many elements from an array as you would like, but for now we are just going to use it to remove one student, Mike, who happened to move to another town:

var students = ['Sam', 'Joe', 'Sue', 'Beth', 'Mike', 'Sarah', 'Steve'];
students.splice(4, 1);
Splice in this example takes two arguments: the index you want to start at and the number of items you want to remove. Since Mike is our 5th student, his index is 4. We only want to remove 1 student, so we put a 1 here. What we are left with is an array with Mike removed: ['Sam', 'Joe', 'Sue', 'Beth', 'Sarah', 'Steve'];

Most of the time we won't know exactly where an item is in our array. Unfortunately the only way to figure this out is to go through the array one item at a time and check. We can write a simple little script that allows us to add or remove students freely:

var students  = ['Sam', 'Joe', 'Sue', 'Beth'];

function addStudent(name){
	students.push(name);
}

function removeStudent(name){
	for(var i=0; i<students.length; i++){
		if(students[i].toLowerCase() == name){
			students.splice(i, 1);
			break;
		}
	}
}
Student Name:
Students:

The only new thing we have here is the word "break". break stops the code from executing any loop it is in: for loop, do loop or switch. So in this case once we find the student we want to remove, we break out of the for loop since we are done.

We will often want to convert an array to a string or convert a string to an array. We are given two functions that can do this simply: join and split. join takes an array and converts it to a string with each element seperated by whatever you pass to join. split goes the other way and makes an array from a string with each new element defined by whatever you pass to split:

var myString = 'apples are good for your health';

var myArray = myString.split('a');	// we break myString apart on every 'a' found.
alert(myArray.join(', '));          // we join myArray back together with a comma so you can see each item
alert(myArray.join('a'));           // now we join myArray back together with an 'a' so we get our original string back

Two other useful functions dealing with arrays are "pop" and "shift". The names are not very descriptive of what they do, but "pop" removes the last item from an array and returns it. "shift" removes the first item from an array and returns it.

var students  = ['Sam', 'Joe', 'Sue', 'Beth'];

while(students.length>0){
	alert(students.pop());
}

Unfortunately by doing this we destroyed our array: it is now empty. Sometimes this is what you want to do. If all you want to do is empty your array, a quick way to do it is to simply set the length to 0:

students.length = 0
Your array is now empty. Even if you reset the length to something greater than 0, all of the data in the array will be gone.

All of the arrays we have been working with are called "Indexed Arrays" since each item in the array has an index that you must use to access it. There are also "Associative Arrays". An Associative Array is a fancy term meaning that each item in the array is accessed with a name as opposed to an index:

var grades = [];

grades['Sam']  = 90;
grades['Joe']  = 85;
grades['Sue']  = 94;
grades['Beth'] = 82;
Associative Arrays act a little differently than Indexed Arrays do. For starters, the length of your array will be 0 in this example. So how do we see what items are in our array? Well the only way to do this is with a "for-in" loop:
for(student in grades){
	alert(student + "'s grade is: " + grades[student]);
}

The syntax for a "for-in" loop is: "for(item in object){". The loop will go through each item in the object and item will be the item's name. In this case item is "Sam" then "Joe", "Sue" and "Beth".

The final thing to note about arrays is that you can actually combine Associative and Indexed Arrays, although this is not usually reccomended because it can cause some confusion. If done properly, however, you can get the best of both worlds:

var students = ['Sam', 'Joe', 'Sue', 'Beth'];

students['Sam']  = 90;
students['Joe']  = 85;
students['Sue']  = 94;
students['Beth'] = 82;

alert('There are '+(students.length)+' students: '+students.join(', '));
for(var i=0; i<students.length; i++){
	alert(students[i]+"'s grade is: "+students[students[i]]);
}

Although this may seem a bit complicated it doesn't contain anything you havn't already learned in this article.

That's all for this lesson! You should now have a fairly thorough understanding of the basic types in JavaScript: Strings, Numbers and Arrays. In our next lesson we will will start working with the Document Object Model, or DOM.

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •