Thursday, February 22, 2024

JavaScript Basics Part 1

This is the first in a 10-part series that will introduce you to the JavaScript language. 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.

Here are examples of the two ways to include a JavaScript file:

<script type="text/javascript"></script>

<script type="text/javascript" src="scripts/YourJavaScriptFile.js"></script>

In the first example, you would place your JavaScript code between the > and < characters, right before “</script>”. Just in case you are completely unfamiliar with how a webpage works, here is an example of how to start your HTML page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE> The Title of Your Page Goes Here </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="Your Name Goes Here">
<SCRIPT TYPE="text/javascript">

The bulk of your webpage (the body) goes here.

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:

apples = apples - parseInt(eat);

This would do exactly the same thing and might be a bit easier to understand. Now that we know how many apples are left we once again let our user know this information.

There are other operators like -= that do similiar things. In total, there are 8 common arithmatic operators that you will use:


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.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles