Article
JavaScript 101 - Part 1
Language Basics
Built-In Functions
In the previous example, we used a single JavaScript statement, without really explaining how it worked:
alert("Welcome to my Web Site!");
Somehow, this single line was able to stop the browser in its tracks and force it to display a message box... Is JavaScript really that powerful? Well, yes and no. You've probably figured out that the text appearing in quotes (Welcome to my Web Site) is what gets displayed in the message box, and you can change this to be pretty much any message you want. What about the rest of the statement?
The word alert is actually the name of a JavaScript built-in function. You can think of a built-in function as "something that JavaScript knows how to do without you having to explain it." Displaying a message box that the user has to click "OK" in is a built-in function because JavaScript knows how to do this, and nowhere do you have to tell it where to display the window, what buttons it should contain, not to mention all the other mundane details involved.
So the JavaScript statement above tells the browser to execute the JavaScript built-in function called alert. Such a statement is called a function call, because you are calling a function. If this sounds like a strange way of putting it, don't worry -- programmers like to make things confusing. Just think of a function as an expert that's really good at doing a particular job (in this case, the alert function is an expert at displaying message boxes). As the author of a script, you want to make use of that expert's skill, so you call the expert on the phone to ask it to do something -- a function call.
Parameters
The alert function is so good at its job that the only detail that it needs from you is the message to be displayed. The alert function wouldn't be much use if it only let you display a fixed message that was decided upon by the function, would it? Using such a function would be like hiring a painter for your house that only knew how to paint in one colour (probably fluorescent green, too!). These bits of information that need to be specified when calling a function so that it does what you want it to are called parameters.
To specify the parameters for a function call, you list them, separated by colons, between parentheses following the name of the function:
function(parameter1, parameter2, parameter3);
We'll be seeing more examples of built-in functions throughout this series of articles, so don't worry if the details aren't quite clear to you yet.
Variables
In just about any programming language, there exists the concept of a variable. A variable is a name you assign to an imaginary "box". That box can contain many different things: a piece of text, a number, or even a date and time. The box can only contain one thing at a time, though. And whatever it contains, you can always refer to the contents of the box by the name that you've assigned to it-the variable.
You create a variable using the var command, followed by the name of the new variable. To assign a value to a variable, you just use the = operator. This is best illustrated with an example. I've stuck a comment on each line to explain what's happening (remember, everything after // on a line gets ignored by the browser).
var a; // Creates a variable called a
a = 5; // Assigns the value 5 to the variable a
alert(a); // Displays a message box containing the value of a (5)
a = "Hello!"; // Assigns the value "Hello!" to the variable a
alert(a); // Displays a message box containing "Hello!"
Not convinced? Try the example yourself:
You can also set the initial value of a variable when you create it:
var b = 20; // Creates a variable called b with value of 20
Finally, since you can use a variable pretty much anyplace where a value would normally go, you can assign the value of one variable to another:
var c, d; // Creates two variables: c and d
c = 10; // Assigns the value 10 to the variable c
d = c; // Assigns the value of c (10) to the variable d
c = 20; // Assigns the value 20 to the variable c
alert(c); // Displays a message box containing the value of c (20)
alert(d); // Displays a message box containing the value of d (10)
Once again, here's the complete code for you to try:
Operations
JavaScript, like any good programming language, lets you take simple values (like numbers and strings of text) and perform operations on them (like addition, subtraction, or even comparison). You can then pass these values to functions or store them in variables. Again, let me show you some examples so you know what I mean:
var a, b, c; // Three variables
a = 10; // Assigns value 10 to a
b = 10 + 1; // Assigns value 11 to b
c = b - a; // Assigns value 1 to c
a = b * 3; // Assigns value 33 to a (* is multiplication)
c = a / b; // Assigns value 3 to c (/ is division)
You can perform multiple operations in a single statement, if you want to. Note that numerical operations obey the same rules of precedence as they do on a scientific calculator-multiplication and division first, followed by addition and subtraction. Of course, we can use parentheses to change this if we want:
a = 1 + 2 * 3; // a = 7
b = (1 + 2) * 3; // b = 9
Recall that variables don't have to contain numbers. They can also hold strings of text... and operations can be performed on strings as well:
var name = "Kevin";
alert("Hi " + name + ", how are you today?");
The code above displays the message "Hi Kevin, how are you today?". Notice how the + operator, which is used to add numbers together, can also be used to stick strings of text together. Notice also that we've used the result of the expression "Hi " + name + ", how are you today?" as the parameter to be passed to the alert function.
Control Structures
Wow, these headings just keep getting scarier, don't they? Don't worry, control structures aren't as complicated as they sound.
All the examples we've seen so far have taken the form of a series of statements that were to be executed in order from top to bottom. Control structures let us change that. Let's start with the most basic control structure, an if statement:
if (condition) statement;
This tells the browser to execute the statement only if the condition is true. For example:
if (a == b) alert("a and b are equal");
That double-equals is not a typo. Where a = b assigns the value of b to a (as shown above), a == b tests if a and b are equal. So the above line displays a message box saying "a and b are equal" if the condition a == b is true. Makes sense, right? Here are a few more examples of conditions for you:
if (a > b) alert("a is greater than b");
if (a < b) alert("a is less than b");
if (a >= b) alert("a is greater than or equal to b.");
if (a <= b) alert("a is less than or equal to b.");
if (a != b) alert("a does not equal b");
Instead of a single statement, you can specify a whole series of statements that should be executed if the condition is true. You do this by putting the statements between braces:
if (name == "Kevin") {
alert("Hi, Kevin!");
// ... more statements here ...
}
Just to complicate things further, there's also an if-else control structure:
if (condition) {
// statements to be executed if condition is true
}
else {
// statements to be executed if condition is false
}
In this case, one group of statements or the other will be executed. The condition determines which.
The two control structures we have seen are the most basic, and most commonly used. We'll save explaining the rest until we actually need them.
Writing Your Own Functions
One of the big time-savers in JavaScript is the ability to write your own functions. We've already seen that JavaScript provides a set of built-in functions (we've already played with the alert function quite a bit), which can be passed parameters to do various useful things for us without us having to worry about how those things are done.
By writing your own functions, you can extend this convenience to sections of code that you write yourself. Complicated procedures that you want to do more than once can be written as functions, which you can then call as many times as you need. Let's look at an example:
function welcome(name) {
var greeting = "Welcome to my Web site, " + name + "!");
alert(greeting);
}
welcome("Kevin");
welcome("Amy");
The code above starts by defining a function named welcome. When called, this function expects a single parameter to be passed to it, the value of which will be temporarily assigned to the variable called name. The function then creates a variable named greeting, and uses the name variable (containing the value passed as a parameter) to create the greeting message. Finally, the message is displayed in a message box using the alert built-in function that we know and love.
With the function defined, we call it twice: once passing "Kevin" as the parameter and a second time with "Amy" as the parameter. The final result of this script is two message boxes displayed one after another—the first greeting Kevin, and the second greeting Amy. Astute readers may point out that this whole thing could have done with two simple calls to the alert function. The point is that we could have had a really big and twisty bit of JavaScript in our function, in which case having the code bottled up in a function would have made a lot of sense and saved a lot of typing when we wanted to use it more than once.