Left Quote    Every day I get up and look through the Forbes list of the richest people in America. If I
- Robert Orben    
Right Quote
[login] | [Register]

Learning JavaScript Basics

by: bs0d
Page: 1 of 10
(View All)


Before we get started I would like to just inform you a bit on the background of JavaScript. In 1995, JavaScript was developed by Netscape Communications Corp (The same company who build the Netscape Navigator). At first, was referred to as LiveScript. Netscape decided to change its name to JavaScript because of its relationship with Java.

Also, JavaScript does not require any special software or tools to execute. In fact, all you're going to need to get started coding is notepad and a browser. Even if you use a browser like Opera or Mozilla FireFox, they will recognize JavaScript in web documents.

The definition of JavaScript is: A scripting language that has the ability to combine HTML and other elements from a programming language all in one package. So JavaScript is as flexible as PHP. In PHP, you can simply jump in and out of HTML. This is pretty much the same with JavaScript. You will see exactly what I mean once you read on through the tutorial.

Once you begin coding in JavaScript this will always be your first line:

This first line of code is going to tell your browser that you will be using JavaScript. Once you have finished coding your document, you will use the following line of code that will tell the browser that you're done using JavaScript at that time.

*All statements in JavaScript will be between the <Script> and </script> tags. Also, all statements in JavaScript must end with a semi-colon (;).

Pretty simple? Programmers say that JavaScript is one of the easiest languages to learn, and it is a great starting point for aspiring programmers. Another reason it is a good place to start is because the JavaScript syntax is quite similar to C. So once you have learned JavaScript, learning C will be much easier.


Now if you're going to use JavaScript in your html document, and you do not want it all cluttered up, then the is a way to hold the javascript in a separate file, and link to it. This would save some space in your html document and could also keep you on track. The following code below indicates the way to link to your external javascript document:

As you can see from the example above, your external javascript documents will need the ".js" extension. So if you decide to create your JavaScript outside of your html document, remember to save your script with a ".js" extension.

*Also just a little extra information, your external JavaScript file does not need to include the <script> and </script> tags


In every programming language, you can add in comments with your program. Comments are lines of code that will not be executed with the rest of the program. It is wise to indicate comments because It can help you remember what you're doing yourself if the project is quite big. Also, it can be helpful for others that may see your program. This can help them learn to code themselves.

Now, there are several different ways to use comments in JavaScript. JavaScript recognizes single line comments, and multiple line comments. If you were to insert a comment that would only span one line, you will use the double slash: //.


To enter multiple line comments, or comments that are going to take up more that one line (like a paragraph) you will use the /* and the */ characters.

Now that we've covered that, lets go ahead and move on to Variables and Constants.


What is a variable? A variable is an amount of data which can change over time (throughout your program). What is a constant? A constant is an amount of data which will never change. When using variables in JavaScript, here are a few rules to keep in mind:

  • A variable can be letters, digits and the underscore (_).
  • A variable cannot contain spaces.
  • A variable has to begin with a letter or the underscore.
  • Variables are 'case sensitive' in JavaScript.


If you are unfamiliar with the term, "case sensitive" - This means that JavaScript will recognize the difference between upper case, and lower case letters for names of your variable. Like, "HI" is different from "Hi" which is different from "hi". So keep that in mind when you're using variables and referring to them in JavaScript.


In JavaScript, to declare your variables you are going to use the VAR statement. You need to declare your variables at the beginning of your program, however it is not required. It is just considered to be good practice.

Example of declaring variables:


In JavaScript, you can have 4 different types of variables in your program. Below is a list and definition for each.
  1. Integer: All positive and negative numbers, zero is also included.
  2. String: Strings are considered to be words and sentences within double quotes.
  3. Floating Point: This type of variable is any number that will contain a decimal.
  4. Boolean: A Boolean variable is that of which will be used in a conditional statement that will need one of two values, True or False.
here is an example of each variable type:

See, in Javascript the data type will be assigned to a variable when you give it its value. And JavaScript can see the type of value you give it and assign it a data type. JavaScript automatically recognizes the data types of variables. You can check your variable type by using the typeof keyword. Here is how you could use this keyword:

This keyword will work for any type of variable in JavaScript.


Now before I go much further, I'm sure you noticed the document.write(); in the code example above. This is how you will display information, or print it out on the screen. There is also document.writeln(); document.writeln(); differs from just document.write(); because it will take the cursor down to the next line. As where in document.write(); you must include the html tag, <BR> (which is a hard line break) that takes the cursor down to the next line.


Another bit of code you might have noticed in the example above, are the "+" signs. The "+" sign is a concatenation character used to combine strings, numerical variables and numerical constants. In order to combine say, two or more strings or numbers, you will need to use the "+" character.

Now, I believe this tutorial will be better than previous tutorials written because of the following:

Here is a button you can click that will display a javascript document that you should be able to write and understand from this point. You can simply view the source to see the code behind it. (In IE it is VIEW --> SOURCE.)


Here is a quick question. What do you think will be the typeof the following variable:
num1= "45";

If you said, "number" that is incorrect. Yes, it is a number and eventhough the variable name is "num1" that does not matter. It could be named anything. What matters is that the values are enclosed in double quotes. So, automatically JavaScript is recognizing the variable as a string. So if you answered "string" then you are on top of this!


But what if you wanted that variable to be recognized as a number instead of a string? Well, that is where parseInt(); function comes to play. So before you can perform arithmetic operations on a group of numbers, you need to know you're dealing with numbers!

parseInt's duty is to convert a string into an integer. It starts this process from the left hand side, and begins converting digits until it runs into a non numerical digit. From this point, the process will stop. Whatever has been converted will automatically be assigned to the variable. If the first character encountered is not a numerical value, then parseInt will display "NaN" - which stands, for not a number.

Now a practice use for parseInt would be if you are using numerical values obtained from user input. So, if they enter, "stupid" instead of a #, you can test with parseInt if it is indeed a number, and if not, re-prompt them to enter a value.

Here is an example of how parseInt(); will work:

As you might see in var1 and var2, parseInt stopped after "7" in var1 because of the "U", and in var2, it stopped after the "7" because of the "U". In var3, it saw the "W" and saw it was not a number (NaN). For var4, it stopped after the number "3" because of the "A", even though after "ABC" numbers pick back up- parseInt stops after the first non numeric digit, not all digits within the variable. var5 stopped when it saw the "." because it is a non numeric digit as well.

Though with parseInt(); JavaScript will not recognize letters, if you do use a minus sign (-), the string will be converted to a negative number. The same concept applies to the plus sign (+) where it will be considered a positive number. BUT, if the "+" or "-" sign appears anywhere else that then first character, they will be considered a non numeric character.


What you needed to recognize floating point numbers? Well, this is where the parseFloat(); function comes into action. parseFloat works exactly like parseInt, except it works with floating point numbers instead of just integers. So when parseFloat comes to a period "." it will interpret it as a decimal point (where parseInt saw it as a non numeric digit). However, if a second period is noticed, parseFloat will see it as a non numeric digit.



Ok, working opposite now. What if we have a number, and want to make it a string? Well, we are lucky that JavaSript has the toString(); function! How you will use this, is by simply adding the toString(); function at the end of your variable name seperating the variable and function with a period.


There is also another way to turn a number into a string, and that is by adding double quotes to it. We will do that by using the method outlined within the code in the example below:

There you have it. Now you know how to convert a number to a string.

Here is a sample JavaScript program using the information we covered:


If you are unfamiliar to what an array is, an array is just a collection of data that is referred to by a common name. Arrays in JavaScript start with element "0." Arrays can offer you a convenient way to group related variables. Also, in JavaScript, data items in arrays can be of different data types. This is unlike most programming languages. Furthermore, JavaScript array elements are not required to be of the same data type. This means, you could have one element as an integer, the next Boolean, another as float and so on. However, if you plan on doing calculations with array elements, the elements must be of the same data type.

Here are some useful advantages of using arrays:
  • Less amount of coding for the programmer.
  • Program will take up less memory, thus executes faster.
  • Makes it easier to process related groups of data.


In JavaScript, it is required to declare any array before it can be used. You can accomplish this by assigning the array a name, ='s sign and the keyword NEW, Then Array (capital A) and the # of elements in parenthesis you plan to use.


<arrayname> = new Array(<# of elements>);

myArray = new Array(50);

*Just make sure that you capitalize the "A" in array on the right hand side of the equals sign. If not, you will get an error.

Now just to sort of discuss why arrays are important and useful. What if you needed to get the average of say, 50 numbers? Without an array, you would write 50+ lines of code. On the other hand, with an array you can accomplish this by 7 or 8 lines of code. And that would be the same if you needed to find the average of 100000 numbers. Instead of writing 100000 lines of code, 7 or 8 will do the trick.

Example of using an array to average numbers:

*In the code sample we used a for loop. We will discuss these a bit later.

Array Length's

JavaScript allows you to find the number of elements in your array with the LENGTH property. This will show you the number of elements in the array. The LENGTH property is a statement just like a variable. Here is how you would use it on an array named, "theArray."


Joining Array Elements

Ok, what if you had an array and you wanted to combine each element to form a single sentence? Well, with the join(); function, it is quite simple! The join function will convert your array elements to a string. And a comma (,) is inserted between each element as it is converted. However, you can specify a different separator.


This would output: How are you this morning?

Notice my join function. it has ' ' included. This makes it output a space between each element. Also doing just, .join(" "); would work. But if nothing was inside the ( and ), it would output: How,are,you,this,morning? It defaults with the comma. If you want anything different, you must specify it. Just make sure you surround it with ' and ' because just .join( ) would make an error.

Sorting Array Elements

You have the ability with JavaScript to sort your array elements, and this is accomplished with the SORT property. It will sort them in ascending alphabetical order. They are arranged according to their ASCII character set. ASCII maps out each character with a combination of eight 0's and 1's. Each letter and number has an ASCII value associated with it.

If sort(); is used on numbers, the numbers are sorted alphabetically instead of numerically. So say an array with: 1,2,3,4,11,22 would sort as: 1, 11, 2, 22, 3, 4. So basically sort(); has to be used with strings.

Here is an example of an array and the sort(); property:

This would output: apples,banannas,mangos,oranges,pears

Just as the .join(); function, you can enter html between the ( and ). So, if you put, .sort('<br>'); this would output each item on a line by itself. And using .sort(" "); would put a space between each item instead of a comma.


Now is a good time to discuss operators in JavaScript. I am also doing to discuss If and If/Else statements because this is when you are going to use many of these operators. There are several types of operators, and they are listed and described below:

Arithmetic Operators: These are they symbols used to calculate values.
  • "+" Addition
  • "-" Subtraction
  • "*" Multiplication
  • "/" Division
  • "%" Modulus (Takes one number and divides it by another number and places the remainder in the variable.)
If you are unfamiliar with Modulus, here is an example of how it works:

In arithmetic conditions, JavaScript follows the order of operations. I think in grade school they taught it as something like, "Please Excuse My Dear Aunt Sally."
  • Parenthesis ()
  • Unary Operations -
  • Mult. and Division (L to R) * and /
  • Add and subtraction (L to R) + and -

It is useful to be aware of the order of operations when working with more than 2 numbers. Here is an example of what I mean:

Relational Operators: These are used when comparing one or more items and will return a Boolean expression.
  • "==" Equals
  • "<" Less Than
  • ">" Greater than
  • ">=" Greater than or Equal
  • "<=" Less Than or equal
  • "!=" Not equal

Logical Operators: used to compare two or more simple conditions at the same time.
  • "&&" = and
  • "||" = or

Something to go along with the logical operators are what are called, "Truth Tables." Truth tables show all possibilities for logical operators when looking at conditions.


Compound Conditions: This is just where you combine two or more simple conditions with a logical operator.



To say, x = x + 1:

Say you took: y = x++; What's going to happen?
y will = x
and then x will = x + 1.

Say you took y = ++x; What's going to happen?
x will = x + 1
then, y = x.


To say, x = x - 1:

If you took y = x--; What will happen?
y will = x
and then x will = x - 1.

If you had y = --x; What happens?
x will = x - 1;
then y will = x.
Not as confusing as you might think. This will help you when using increment and decrement operators to know the value of your variable through the process of the program.

Math Object

The math object is a built in object which includes math constants and functions. Theres no need to create any math object, because it already exists automatically when using JavaScript.

There are four useful functions in JavaScript:
  • Math.random() - Will generate a random number between 0 and 1.
  • Math.ceil() - Will round your number up to the next integer.
  • Math.floor() - Rounds your number down to the previous integer.
  • Math.round() - Round your number to the nearest integer.

Make sure when using the math functions, be sure to capitalize the 'M' - Just to brief you more, here's what each function would do with the number 3.23:
Math.ceil(); would increase the number to 4.
Math.floor(); would decrease the number to 3.
Math.round(); would make the number 3. But say if the number was 3.5, the function rounds automatically to the nearest even integer.

Below is a line of code using Math.floor and Math.random that generates a number between 1 and 10.

Lets put the math.random to use on a large scale. From the code sample below, we're going to generate 7000 random numbers. We'll also keep a random total and calculate the average. And we'll use the Math.Round() to calculate the average to the thousandths place. Check it all out below:

This is a perfect example why you should use loops. Imagine having a user input 7000 numbers, or even hand writing them yourself. Let alone finding the average!


This is where you will use your conditions. You set a condition in the program and have it perform certain tasks according to the condition.

Here is the syntax of an If statement in JavaScript:
statement3 on...

*If you are only going to use one statement in JavaScript, then you will not need { and }. These are used for conditions with multiple statements. If you put multiple statements and do not use { and }, then only the statement executed will be the statement immediately following the condition.

Now here's a practical example of using an "if" condition:

So what do you think will happen in that condition? Well, the condition is true: x is not equal to 24, so the values of a, b and c will equal what was assigned to them.


In the examples above, the condition was true. But what if it was not? Then what would happen? If you only had an If statement, nothing would happen. It would skip the statements between { and }, and proceed to execute the rest of the program. But what if you wanted something else to occur if it was not true? This is where you will use an If/Else statement.

Here is the syntax of an If/Else statement in JavaScript:

if (<condition>)
{ //used only for multiple condition circumstances statement1;
} else { statement1; statement2; }

*Again, if you're only going to use one statement for if, and one for else- the { and } are not required.

Here is a practical example with an If/Else condition:

So, what do you think happened here? x is = to 99, so the statements for true are executed. y = y + 10 and z = z / 14.


You can input data directly into your JavaScript program from what is called the Window.prompt dialog box. This dialog box is displayed with a caption you specify, and two buttons (ok and cancel). Automatically, the information entered will be considered a string. So, if you want to change the value to a number, just use the parseInt statement. The argument of the statement is the caption you put in the box. Like, "what is the answer?"

syntax of using window.prompt:

<a_string> = window.prompt(<the caption you want to appear>);

example of using it in a program:

The "if" statement checks to see if the variables match, if they do- that means the person entered the correct answer. If not, they answered incorrectly or did not enter a numerical value. Technically, you could run another if statement to check if the results were = to "NaN" then if that was true, make them enter an actual numerical value.


In addition to window.prompt, there is window.confirm(); The difference is that it will display two buttons, 'Ok' and 'Cancel' which can be used for an if statement for True or False results.

Check out the syntax:

OurVariable = window.confirm("Message you want displayed.");

Look at the code below to see exactly how it works:

The message "Do you like spring" is displayed in a dialog box that appears when the page is loaded. If the user selects 'Ok' then the program will print out, "I like spring as well." If the user selects 'Cancel' then the program will print out, "Why don't you like spring?" on the screen.

Now on to a simple program using a bit of what we covered.


Loops are an important part of JavaScript. Loops control your program to whatever limits you set them to. There is a loop which executes a group of statements a finite number of times. Then there is an infinite loop, which is a loop that will never terminate.

There are 3 types of loops used with JavaScript:

  • FOR loop
  • DO WHILE loop
  • WHILE loop

It is to your advantage to use loops when you need to execute a group of statements over and over. Again, this cuts down on coding for you, and also allows your program to execute faster. You want to build your programs short and powerful, not long and slow.


Although you have already seen a for loop used earlier in this tutorial, I will still go ahead and describe how they are used.

for (<initial value> ; <condition = true> ; <increment value>)
and so on...;


So what is the control variable in the code sample above? The answer is "a" do you see?


We have not discussed while loops, but there is a place and need for them in JavaScript. If you were to use a while loop, this is how you would construct it:

while (<condition = true>)
and so on...;

And this is what one might look like with actual information plugged into it:

That is it for the while loop.


This is similar to the WHILE loop, except it's just arranged a bit differently. Here, take a look:

and so on...;
while(<condition = true>);

Like all of the rest of the loops, the statements you need executed a number of times are between the { and the }. But unlike the While loop and the for loop, the condition is underneath the statements. Just be sure you say "do" at the beginning when using this loop


Did you notice anything different? Look at the condition of the loop. At the end, we must use the semicolon. This is also the only loop where a semicolon is required at the end of the condition.


What if you needed a loop, but once the loop reached a certain point you also needed it to stop within the boundaries you already set? JavaScript has the BREAK statement specifically for this purpose. So if you were caught in an infinite loop, the BREAK statement could get you out of it. Once JavaScript reads the BREAK statement, the loop is dropped.

I know, you want to see it in action! So in the code sample below, I will create an infinite loop (one that would normally never end), but then use the BREAK statement to end the loop once it has reached a point I specify...

Do you see how it works?


Like the break statement, there is also the continue statement. If you use the continue statement, it will stop execution of the loop and return back to the beginning of the loop. This means, if you place the continue statement in the middle of your loop, any statements underneath will not be executed once the condition for continue has been met. The purpose or intent behind using it is to check for special exceptions inside the loop --and skip them without disrupting the normal flow of your loop.


What do you think occurred above once executed? When the loop is processed, it takes the value of x and adds one to it. Then it checks to see if x is = to 3, if not - it will process the "document.write" statement. So the output would be: 1,2,4,5. Skipping 3 because when it got to continue, it went back up to the beginning again.

This seems like a good place to stop and show you a bit more examples using what we learned.


Functions can play an important role in your JavaScript programs. Functions are a set of statements that are put together for a single purpose. You create a function for blocks of code you might need to re-use throughout your program. Using functions make your program modular and flexible. Also, it will be easier to read and follow through. There are three different ways they can appear when calling them in JavaScript:
  • On a line by itself
  • Right hand side of equal sign
  • In a "document.write" statement

How they work

Ok, when a function is called upon, the control is transferred to the function and the statements in your function are then executed. Once complete, control returns to the command where you called the function or to the next line.

Return Statement

You use the return statement to return a value back to the main program. Here is how you would use the return statement:

Naming your functions

When you name your functions, you want to be sure and make the name unique. The rules are the same when naming your variables. Here I will show the examples of some functions, and the different ways they can appear.

In the code sample above, this function call is on the right hand side of the equal sign. You see how it works? When you call the function (by its name) in parenthesis put in the 2 variables that will take the place of 'a' and 'b' and the statements in between the { and } will be executed using the variables you put in it.

This is how you would call the function in a "document.write" statement. It will work the same as above, its just called differently.

This is how you could call a function where its on a line by itself. You just replace the return(); with a document.write that will print your result when you call it (if that's what you desire).

One last bit of information on functions, you can also use them to work with strings, so you're not limited just to use them with numbers or anything.


Understanding it more? The function is food, the identifier 'fruit' is the parameter. So fruit is a string used to print the multiple items. We called the function 3 times.

The possibilities for function are endless, and you can make them as complex or as simple as you wish. From adding number or bolding text to performing complex arithmetic operations and multiple text manipulations.


First, events are bits of code that link an action by a user, to an action performed by the computer. The action can be a mouse action or key press on the keyboard, or even loading / unloading a webpage.

There a numerous events that can be used within your Web Page, it's just where you would use them varies from place to place. Below are the different categories of events you will use:

  1. Keyboard Events
  2. Mouse Events
  3. Selection Events
  4. Misc./Other Events

Now we will go a bit more in depth of each category, describe them and also provide a list of some of the most commonly used events.

Mouse Events

Whenever a user performs actions with the mouse, these are the events that will detect the specific actions, and then you can act accordingly.
  • onclick - When the left mouse button has been clicked once.
  • ondblclick - Detects when the left mouse button has been clicked twice very quickly.
  • onmousedown - Detects when the mouse button has been held down.
  • onmouseup - Will detect when the mouse button has been released.
  • onmouseover - When the mouse cursor moves over the top of an element.
  • onmouseout - Will detect when the mouse cursor has moved off an element.

Here is a simple example using one of the events above that should give you an idea of how you can use these in your JavaScript programs.

What occurs in the form above is that when you press the button (Press Me) once, the text box to the left (text1) will indicate you pressed the mouse button. And when you double-click the button, it will indicate the double-click.

Selection Events

These events detect when focus has been given to a certain control on a form.
  • onselect - Will detect when an element has been selected.
  • onfocus - Signals when an element has been given focus.
  • onblur - Signals when an element has lost focus.

Check out this code sample below. You can use it as a guide to give you an idea of how to work with these events.

Miscellaneous Events

Here are a few common events used with JavaScript, but they do not necessarily fit in the outlined categories above.
  • onchange - This will detect when data (within a form element) has been changed.
  • onload - Detects when your webpage has finished loading.
  • onunload - Signals when a webpage has been unloaded (when someone leaves the page).
  • onabort - Will detect when the loading process of a webpage is canceled.
  • alert - this is sort of like "window.prompt" but only used to notify a user when an event has occurred, and only the Ok button is displayed. (Can be displayed as alert(); or window.alert();)

Take a look at this code sample and see a few of the Miscellaneous Events in action.

This works the same with "onabort", "onunload" and so on.

Window Objects

In addition to the Misc., Keyboard, mouse and selection events, there are some window objects you can use to perform specific tasks. Below is a list of a few commonly used window objects you can use within your programs to make them more efficient and user friendly.

  • window.print - Will print the page you see on the screen.
  • - Can open a new window, you can set the properties as well.
  • window.close - Will close the current window.
  • window.status - This can display a message in the status bar of your window.

Check out the code below and you can get an idea of using these objects in your programs.

Take a look at the "open" button. You can open files or even urls. You can set the properties, they go like this:'file or url', 'open it within the current window','set toolbar to yes or no, status bar yes or no, height and then width').


If you plan on involving JavaScript a bit more in your Web Pages, you can set the background and foreground colors using JavaScript. The foreground will be the color of the text on your webpage. The built-in functions below will set these properties:

  • fgColor: Set your foreground like this, document.fgColor="red";
  • bgColor: And set the background like this, document.bgColor="green";

You can either set the colors using the name of the color, or you can use the hexadecimal format. I am sure you have seen them before, but here is an example anyway...

Keyboard Events

The most common keyboard event used is the onkeypress event. This even can check to see if a key is pressed on the keyboard. Here's a list of some keyboard events.

  • onkeypress - Detects a keypress from the keyboard.
  • keyCode - Records the ASCII value of a letter pressed on the keyboard.
  • onkeydown - This event is triggered when a key has been pressed down.
  • onkeyup - Is triggered when a key from the keyboard is released.

These keyboard events can get quite interesting if you're familiar with the ASCII values of the key's on the keyboard. Check out this code sample:

In order for this to work, press the capital "A" and the textbox will indicate you doing so. If you were to press anything else, the program would not work.


I feel that by now I have covered a wide range of the basics of programming in javascript and writing your own programs. You could go into more detail of each topic covered, but the intent is to introduce you to it, and it will be up to you to follow through with the language. I hope that the extra code samples and the sample code programs did provide additional understanding of the concepts. Javascript is relatively easy to learn and can be quite useful for your Web Pages. I hope that you found this tutorial helpful on your way to learning something new.

-bs0d |

1  |  2  |  3  |  4  |  5  |  6  |  7  |  8  |  9  |  10  |  
Next »

No Comments for this page.

You Must be logged in or a member to comment.

Tutorial Stats

Tutorial Stats

3 Total Comments
4.66 Rating of 5 (3 Votes)


Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article



· Getting Started with Ajax
Your Article Here

"" Copyright © 2002-2018; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank