Javascript
Javascript
To start off,
we'll explain what JavaScript is.
JavaScript is an scripting language that is primarily used for creating interactive features on
webpages. It can be used to create menus, validate forms, swap images, or just about anything
else you can think of to do on a webpage. If you have ever taken a look at Google Maps or
Google's GMail service, you have an idea of what JavaScript is capable of today.
Since JavaScript is currently the only scripting language supported by every major web browser
(Internet Explorer, Firefox, Netscape, Safari, Opera, Camino, etc), it is very widely used. When
code is rendered by your web browser, like JavaScript usually is, it is called a Client-Side script.
JavaScript can also be run on a web server to generate HTML documents, thus running as a
Server-Side script. Although its use is usually limited to client-side scripts, JavaScript can be a
very powerful server language as well.
If you are going to be writing JavaScript code, all you really need is a text editor and a web
browser. Knowledge of HTML and CSS will definitely help, and if you want to use your
JavaScript skills on a website, you are going to also need your own website. If you already have
your own website, great! If not, there are plenty of free servers available that you can choose
from to host your pages.
As for a text-editor, if you are using Windows than you should already have NotePad installed.
Although this will work for editing JavaScript, HTML and CSS, a more robust editor would be a
good idea. My personal favorite is EditPlus, which has a free trial period of 30 days, but you can
use it indefinitely if you are willing to put up with its nag screen. If you like EditPlus however,
and you continue to use it, you should register it.
Now that you know what JavaScript is, let's get started with your first script!
First, we need to know how to add JavaScript to an HTML page. JavaScript can be added in one
of two ways: You can place Script tags in your webpage and place the JavaScript code inside of
those. Or you can place all of your JavaScript code in another file and link to it with a Script tag.
Either of these methods is perfectly valid, but they have different purposes. If you just have a
short piece of code that is only going to be used on one page, placing that code in script tags is a
good way to go. If, however, you have a large piece of code that you are going to be using on
several pages, you will probably want to place that JavaScript code into a separate file and link to
it. This is done so that people do not have to download all of your code every time they visit a
different page. They download it once and then their browser saves it for future use. If you are
familiar with CSS (StyleSheets), they pretty much work the same way.
<script type="text/javascript"></script>
<BODY>
The bulk of your webpage (the body) goes here.
</BODY>
</HTML>
You will want to save this file somewhere on your computer with an ".html" extension. So the
full file name would be something like "JavaScript_Lesson1.html". After you save it, just
double-click on it to open it in your default web browser.
Just about every programming language in the world is focused around things called "variables",
and JavaScript is no different in this respect. A variable is simply a piece of data with a name
attached to it. It can contain a number, a word or sentence (called Strings) or an Object, which
we will talk about later. If you wanted to tell your code that you had 5 apples, you might create a
variable named "apples" and give it a value of 5. So let's do that now. In JavaScript, you use the
"var" keyword to define a variable. Note that JavaScript is case-sensitive, so "var" is not the
same as "VAR" or "Var".
var apples = 5;
There are two important things to note about this short piece of code. First, you should be aware
that JavaScript is a "Weakly Typed" language. This means that when you define your variables,
you do not need to say what types they are: whether they are numbers, strings, objects, etc. In
many other languages, you must make this distinction.
Second, note the semi-colon (;) at the end of the line. This tells your JavaScript interpretor that
you are done with what you are currently doing which, in this case, is setting your "apples"
variable to 5. Although semi-colons are not necessary in JavaScript, it is a good practice to get
used to using them.
Okay, so your code knows that you have 5 apples. Now what? Well your code might know that
you have 5 apples, but nobody else does. Let's tell them! One of the most common methods to
display a simple message to a user is by sending them an alert:
var apples = 5;
alert('There are currently ' + apples + ' apples!');
If you test this script, you will see a window on your screen that says "There are currently 5
apples!". This is a good time to introduce Strings and what we call String concatenation. A string
is just a bit of text and can contain any text that you want. In JavaScript, we tell our code that we
have a string by enclosing it in either double or single quotes (" or '). You can use whichever
type of quote you prefer. The plus (+) signs in our above example tell the code that we are
concatenating onto (or simply adding onto) the previous string.
So what we have is the string 'There are currently ' followed by our apples variable (which is 5)
followed by another string, ' apples!'. Put them together and we get "There are currently 5
apples!". Our "alert" takes whatever is passed to it (whatever is between the parenthesis) and
simply opens a window with that text.
What if we want to let our user eat an apple? One way to do that would be to prompt them for
how many apples they would like to eat:
var apples = 5;
alert('There are currently ' + apples + ' apples!');
var eat = prompt('How many apples would you like to eat?', '1');
"prompt" is another built-in function, similiar to "alert". Instead of just showing information,
however, it also takes input from the user. In this case we are asking our user how many apples
they want to eat. The '1' in our code tells the "prompt" function that our default value for how
many apples to eat is 1. So people usually only eat one apple at a time. The user can change this,
however, to any number they want. Once the user clicks the "OK" button to the prompt, the "eat"
variable gets set to their response. So if they type in that they want to eat 2 apples, eat now
equals "2".
So if our user has eaten 2 apples, there are 3 left, right? Well let's do some basic math and show
this.
var apples = 5;
alert('There are currently ' + apples + ' apples!');
var eat = prompt('How many apples would you like to eat?', '1');
apples -= parseInt(eat);
alert('Now there are only ' + apples + ' apples!');
Two new things here. First, we have a call to "parseInt". parseInt takes in a string and returns a
number. Since we have to have a number to do math, what this does is help to gaurantee that we
have a number. If our user entered "2 apples" in the box, parseInt turns this into the number 2.
Next, we have the "-=" operator. "-=" means that you want to subtract whatever is on the right of
the operator from whatever is on the left of it. So we are subtracting our "eat" variable from our
"apples" variable. You could also write this line as:
+
-
/
*
+=
-=
/=
*=
That's it for this lesson. Next time we will continue by adding some validation to our code, we
will introduce the if and else statements, and briefly introduce you to functions.
Part-2
This is the second in a 10-part series that will introduce you to the JavaScript language. In the
last article, we wrote a simple script that involved variables, alerts, prompts, string concatenation
and some basic arithmatic operators. To test the script we wrote, you can click here. If you don't
fully understand any of these concepts, you should read, or re-read the first article.
If you tested the script we wrote in the last article, you might have noticed that the result you got
from the prompt needs some validation. When the script asks you how many apples you would
like to eat, you could enter a number greater than 5, a number less than 0, or something that isn't
even a number at all. In each of these cases we would like to inform our user that what they
entered is not valid.
Since there are only 5 apples in our script, that is the most apples that our user can take. So we
will start by checking to see if the number they entered is greater than 5.
var apples = 5;
alert('There are currently ' + apples + ' apples!');
var eat = prompt('How many apples would you like to eat?', '1');
The main concepts that we are introducing here are the "if" and "else" statements. If and Else
statements are fairly simple to understand. If you look at the code above, you could say "If the
user selected more than 5 apples to eat, tell them that there are not that many apples. Otherwise,
let them eat as many apples as they entered".
The slashes, //, in the above example tell our code that we have a comment. A comment is part of
your code that is not executed. It is generally used to describe functionality of the actual code so
that you do not have to read through code to figure out what it is doing. If, for example, you had
a very lengthy piece of code that validated inputs on a form, it would be a good idea to place a
comment saying something like "The following code validates the user input for the contact
form". This way if anyone else looks at your code, or if you yourself look at your code several
months down the line, you know what it does right away.
There are two ways to write a comment in JavaScript. The first, as you have already seen, is with
//. Anything following a // on a line is considered to be a comment, and is thus ignored when
your code is executing. The other way is with /* and */. If you place these in your code, anything
between them is ignored.
/*
if you need a longer comment, as is often the case,
it is usually a good idea to use a "block comment".
There are two other cases that we discussed, however. What if the user enters a number less than
0? What if they enter a value that is not a number? The first case you should now be able to work
out for yourself. The second case requires the addition of another built-in function, "isNaN".
When you are trying to convert something to a number, as the parseInt function does, a value of
"NaN" is returned if the function fails. NaN stands for "Not a Number". If you called parseInt on
the value "apple", for example, you would get NaN back because the word "apple" is not a
number.
var apples = 5;
alert('There are currently ' + apples + ' apples!');
var eat = prompt('How many apples would you like to eat?', '1');
By now, all of this should make sense to you. First we check to see if they entered an invalid
value. If they did, we tell them. We then check to see if they entered more apples than exist, and
then if they entered a number less than 0. If all of these checks pass, we let them eat as many
apples as they entered. The one adjustment we made to our code was to change "if(eaten > 5)" to
"if(eaten > apples)". We did this so that if we later change the number of apples we have, "var
apples = 5;", we only have to change it in one place. Getting into a habit of always using
variables in your code is a good idea. If you "hardcode" values, like we previously had in
"if(eaten > 5)", you will very often end up searching for those hard-coded values for hours
making sure you have found and changed them all.
If the user entered an invalid value in any way, you might want to ask them again how many
apples they want to eat. One way to do this would be to copy all of your code several times. This
usually is not a good idea, however. What if the user enters an invalid value again, or again after
that? You could keep copying your code but you can see how this would get very inefficient and
make your code very difficult to maintain.
The proper direction to go in this case is to use what we call a function. A function contains a
block of code that does a certain task. You have already seen functions in use. "alert", "prompt",
"parseInt" and "isNaN" are all functions that are built into the JavaScript language. The
advantage of using a function is that you can execute the same block of code again and again
without having to copy your code. You execute a function by writing its name followed by a set
of parenthesis, (), with any values sent to the function in between the parenthesis.
var apples = 5;
function eatApples(){
alert('There are currently ' + apples + ' apples!');
var eat = prompt('How many apples would you like to eat?', '1');
Here we wrap all of our code in a function called eatApples. You will notice that each time a
user enters an invalid value, we re-call our eatApples function, "eatApples();", so that they can
enter a new value. Once they enter a valid number, we either let them eat more apples or if the
apples are all gone, we tell them this. We introduce one new function here, "confirm". The
confirm function simply gives an "OK or Cancel" prompt to the user. If they click "OK", it
returns a value of true. If they click "Cancel" or just close the window, the confirm function
returns a value of false. So in our example, the eatApples function is only called again if the user
clicks "OK".
One final thing to point out in this lesson is variable scope. You might have noticed that in our
previous example, we moved our apples variable outside of our eatApples function. This makes
our "apples" variable a "global variable", meaning that the same variable is accessible from any
function. The "eat" variable, on the other hand, is a local function and only exists inside of our
eatApples function. In addition, each time we re-call the eatApples function, the eat variable no
longer exists until we define it again with our prompt.
To see this concept in action, we will write two simple counting functions:
function counting1(){
var count = 0;
count++;
alert(count);
}
var count = 0;
function counting2(){
count++;
alert(count);
}
If you click each button a few times you should notice that counting1 always gives you the same
value, 1. counting2, on the other hand, gives you an incrementing number. Why does this
happen? Well, let's just look at counting1 first. You'll notice that each time counting1 gets
executed, the first thing that happens is that we create a count variable and set it equal to 0. Our
next line adds 1 to our count variable.
The ++ operator is something we have not seen before. count++ simply adds 1 to count. In other
words it is exactly the same as writing "count += 1" or "count = count + 1". Since adding 1 to
something is a very common action in programming, there is a method specifically for doing
that. The -- operator likewise subtracts 1 from a variable: "count--".
Each time our counting1 function performs "alert(count)", it is telling us the value of our new
count value which has just been set to 0+1.
Now let's look at counting2. You'll notice that the count variable in this case is outside of our
function. Even before we call the function, count is set to 0. When you call counting2, the first
thing you do is add 1 to our count variable. Since we are not resetting count to 0 again, like we
were with counting1, our count variable keeps going up and it works like we would expect it to.
That's it for this lesson! You now have a basic understanding of some of the fundamentals of
programming and of JavaScript in particular. Next time we will introduce loops and forms.