Your First JavaScript: An Alert Box
For some strange
reason, most programming classes and books have you write your first
program to put "Hello World" on the screen. We can have
HTML put words on the screen just fine; so our first JavaScript
won't do that. Instead, it will say, "Welcome to Java Class"
or whatever you would like it to say in a little alert box just
like the one you saw when you opened the syllabus page.
Open Notepad and type the following:
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<script language="JavaScript">
alert("Put your message here");
</script>
</body>
</html>
Save your file as Alert.html in a folder with
your name in My Documents. Then open the file from a browser. If
you typed it correctly, you should have an alert box. You
have just written your first JavaScript!
Basic Programming Skills in this Bit
of Code:
- Your JavaScript is mixed right
in with the HTML.
- The first thing you do is tell
the browser to get ahold of the JavaScript parser.
<script language="JavaScript">
- Notice that JavaScript uses
<> just like HTML tags. That is because the browser reads
HTML and needs to understand that what is coming is JavaScript.
</script> tells the browser that the rest of the code isn't
JavaScript. It's just like closing a regular HTML tag.
- Most programming and scripting
languages have large collections of pre-written programming that
you can use in your own programming. These bits of code are called
functions or methods, depending on the language.
Here we are using the function alert(). Functions are marked with
() in most languages. The parts inside () are called parameters
or arguments. Each parameter or argument is a piece of information
the function needs to work. In this case, JavaScript needs to
know what you want the alert box to say.
- Notice the " " around
the message. " " tells most programming languages that
the characters inside is what is called a String.
Computers store different types of information differently. For
example, numbers are usually stored differently than letters.
The " " tell JavaScript to hold that information as
a String. A String is one data type.
- There is a ; at the end of the line that creates the alert box. A semicolon
marks the end of one thing the computer has to do in many programming
and scripting languages. The part before the ; is called a statement.
Most programming languages can't work if you forget the ;. However,
JavaScript is more forgiving. You can just type the next statement
on the next line, and JavaScript will understand that it's another
command.
- Try a change in your code. Copy your alert
statement right beside the first one. Take out the ; between them
and change the message in the second alert(). Preview your file
and see what happens. Then add the ; back in and preview your
file. Third move the second alert to the next line and see what
happens.