Learn Javascript


JavaScript is a scripting language designed to be embedded in Web pages to add more functionality and dynamic behavior to otherwise static and boring HTML. Using JavaScript you can write smarter web pages than with just plain HTML. These pages can know about their users type of browsing being used, his/her preferred language, redirect the user to another page, or find out what page the user is coming from and so much more.

On daily basis JavaScript is more preferred choice than alternative server-side solutions when it comes to validating HTML forms, manipulating form data as well as scripting cookies amongst many others.

JavaScript is NOT Java!


Beginners tend to confuse Java and JavaScript. Although both languages can be executed in the user's browser, and in spite of the incomplete syntactic resemblance JavaScript is NOT Java.

JavaScript is mainly used to manipulate the browsers' properties and behaviors, whereas Java is a full-fledged programming language with support for networking and graphics programming.

Your First JavaScript


JavaScript is embedded inside your HTML documents within <SCRIPT> and </SCRIPT> tags. Everything between these tags is considered as JavaScript, thus passed straight to your browser's JavaScript interpreter. Let's try out a very simple JavaScript example:

alert("Hello World from JavaScript");


Now, to try the above example, simply create an HTML document with your favorite editor, insert <SCRIPT> and </SCRIPT> tags inside the BODY section of the document, and paste the above code between these tags:

01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 


<html>
  <head>
     <title>My first JavaScript</title>
   </head>
   <body>
   <script>
     alert("Hello World from JavaScript");
   </script>
   </body>
</html>



If it is your first JavaScript tutorial, we want you to study the above example closely.

We're using alert() window method to tell the browser to display a message alert. We'll talk more about alert() in our Client Side JavaScript tutorials later on. The other most commonly used methods is document.write() method, which writes the text into your web pages. Consider the following example that displays our above ``Hello World'' example inside HTML instead of as an alert box:

01 
02 
03 
04 
05 
06 
07 
08 
09 
10 
11 


<html>
  <head>
     <title>My first JavaScript</title>
   </head>
   <body>
   <script>
     document.write("<h1>Hello World from JavaScript</h1>");
   </script>
   </body>
</html>


Try out the above two examples, and play with it as much as you want. In our examples throughout this article we will omit <SCRIPT> and </SCRIPT> tags to avoid unnecessary redundancy.

Comments


So far our JavaScript example consist of a single line. Once you start doing some real tasks, the things can easily get out of hand, even for advanced JavaScript programmers.

Besides, JavaScript codes can get pretty cryptic pretty soon (sometimes way too soon), and by the time you come back to your previously written code after a week or so,you will have hard time understanding your own codes. For this reason JavaScript supports delimiters called ``comments'', to help you document your code.

Comments in JavaScript come in two flavors, single-line comments, and multi-line comments.

Single line comments are perfect for annotating your code line by line. They start with // (two consecutive forward slashes), and everything till the end of that line is considered comments:



alert("I love comments!"); // telling the world how we feel about comments
  // Now let's see if the user likes comments or not?
  confirm("Do you like comments?");


Multi-line comments can span several lines. This is perfect for documenting your codes, or even commenting out a big chunks of obsolete code. These comments start with /* (forward slash and asterisks) and end with */ (asterisk and forward slash). Everything between these two delimiters are considered comments, thus completely ignored by the JavaScript interpreter:








  /*
    Following line prints a "Hello World" example. Why?
    Because no one would take this tutorial seriously if we hadn't started
    it off with rudimentary Hello World!
  */
  alert("Hello World from JavaScript");


As you see, multi-line comments permit us to write large chunks of commentary inside our codes, thus making it perfect for documenting our programs for later use.

You can frequently catch people talking to themselves in their commentaries. They say this helps them to organize their thoughts before they actually start writing the code. Do whatever suits you; use comments, abuse comments.

Statements


Programming in any other language is about writing statements. In JavaScript statements are directions you will be giving to the JavaScript interpreter throughout your programs. They are analogous to saying ``do this'', ``do that'', ``don't do this'', ``don't do that''. Sounds like orders? That's right! Statements are orders given to the JavaScript interpreter.

So far we have already used couple of statements in our previous examples. Recall alert("Hello World from JavaScript") example earlier. It's a statement telling the browser to display an alert box. We have also used confirm("Do you like comments?") statement, which tells the browser to display a confirmation box with ``Ok'' and ``Cancel'' buttons.

Statements in JavaScript can either reside in their own lines, or can share the same line with other statements. In latter case, however, a semi-colon (;) become mandatory to separate individual statements:

alert("Hello"); alert(" World");


Above line consists of two consecutive alert() statements separated with semi-colon (;). Although no semi-colon is required if the statement is the last statement of the line, we recommend you make habit of using semi-colons after all statements. If you are planning to learn other programming languages, most of them tend to require semi-colons at all times, so better be ready.

JavaScript Functions

The very moment you find yourself writing redundant code over and over again, you have a need for functions. Function is a collection of code designed to perform a distinct action. So far we have been using three build-in functions throughout our examples, alert(), document.write() and prompt(). Now it's time to create our own functions.

Suppose, we have a program, which needs to compute the area of multiple triangles. Since this operation, that is, computing the area of a triangle, will be needed multiple times, it's a good idea to create a function for it to prevent ourselves from writing the same code over and over again.

You create a function in JavaScript with function() { } construct. General syntax for a function is following:





function some_name (arg1, arg2, ...) {
    // some operation
    // and return some value, such as the result
    // of a final computation
  }


Function can be called in JavaScript by its name, followed by opening parenthesis, followed by optional arguments, and finally a closing parenthesis. In the end of the function you should simply return a final result of a computation, if one required.

Let's create a function to compute an area of any triangle, given its width and height:




function triangle(width, height) {
    var area = (width * height) / 2;
    return area;
  }


Now we can compute the area of any triangle by simply calling triangle() function with 2 arguments and save us from having to write the formula each time:









var width;
  var  height;
  while ( !width ) {
   width = prompt("Width of the triangle:", "");
  }
  while ( !height ) {
    height = prompt("Height of the triangle:", "");
  }
  alert("Area of this triangle is " + triangle(width, height) );

 

JavaScript Conditional

Making decisions is an integral part of any programming language, including JavaScript. They allow your programs to choose from alternative actions to be taken based on a condition.

if statement is very similar to while() statement, but the contents of the brackets are executed once if the conditional inside the parenthesis is true. Following example prompts the user an ID, and will greet the user kindly only if his ID is ``Geek''. If his ID is not ``Geek'', will keep prompting a proper.

In this example we will use a prompt() JavaScript function, which displays a dialog box asking the user to type some text in. First argument passed to prompt() is the question, and the second argument is the default text to be displayed inside the text area. prompt() returns whatever the user typed in, or null is the user clicked Cancel button:






var name = prompt("What is your name?", "");
  if ( name ) {
    alert("Hello " + name + "!");
  } else {
    alert("Hello guest");
  }


The above example prompts a user his name. Then, using if/else statement checks if the user told us his name. If so, greets the user with his name, otherwise greets him as 'guest'.

It's not required that if statement should be followed by else. if statement can exist alone. We could omit the else part from the above example:




var name = prompt("What is your name?", "");
  if ( name ) {
    alert("Hello " + name + "!");
  }


Now the user will be greeted only if we know the user's name. Otherwise nothing happens. Following example is a little extended version of the above example, but checks for a specific username. If it recognizes the user, delivers a message:




var name = prompt("Who are you?", "");
  if ( name == "coder") {
   alert("Really? I am a coder too!");
  }


If your application requires it, you can nest multiple if/else statements. General syntax for this is like following:









if ( some conditional ) {
    // some action here
  } else if ( some other conditional ) {
    // another action here
  } else if ( more conditionals ) {
    // more actions here
  } else {
    // done!
  }

 

JavaScript Loops

JavaScript performs several types of repetitive operations, called ``looping''. Using these operations you can iterate through the list of array elements, repeat certain operations until some condition is met, or just keep repeating a certain operation and crash the browser (Doh!). Well, the latter case is not the primary design objective of loops, but just a side effect created by reckless programming.

for () - loops


The basic type of loop operation is known as -loop. Inside the loop there should be at least 3 statements; the first is the initial state, the second is the condition, and finally the last is the increment operation. Everything between opening and closing brackets are executed until the middle statement, that is condition is true (OPERATORS).

Consider the following example, which prints numbers 1 through 10 to the browser:




for (var i=0; i <= 10; i++ ) {
  document.write(i + "<br>");
}


Let's study the code closely. The first statement of the loop is var i=0, which is creating a loop's initial state by initializing a variable with 0 (zero) value. The second statement i <= 10 is setting a up a condition. Everything between the brackets will be repeated until this condition returns false. The last statement, i++ is incrementing the value of i by one at each iteration. In other words, it will repeat everything inside the brackets until i is less than or equal to 10.

Following is a more useful example, which will display a drop-down menu of years from 1900 to 2005.





document.write('<select name="year">');
  for (var i=1900; i <= 2005; i++ ) {
    document.write('<option value=' + i + '>' + i + '</option>');
  }
  document.write('</select>');



Now imagine how much time it would take you to generate something like this with plain HTML.

Another most commonly used looping tasks is iterating over a list of array elements. Recall states array we built in earlier sections. Suppose we wanted to list all the states. Following code will do just that:




document.write("<h1>US States</h1>");
  for (var i=0; i < 49; i++ ) {
   document.write( states[i] + "<br>" );
  }


We could make the code more smarter by letting it figure out the size of the array on its own by replacing i < 49 with i < states.length:




document.write("<h1>US States</h1>");
  for (var i=0; i < states.length; i++ ) {
   document.write( states[i] + "<br>" );
  }


You can nest loops as deep as you wish, as long as you know what you are doing. Following example uses a nested for-loop to generate a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividents, and inner loop will be responsible for generating lists of dividers for each individual number:







document.write("<h1>Multiplication table</h1>");
  for (var i = 2; i <= 9; i++ ) {   // <-- this is the outer loop
    document.write("<h2>" + i + "</h2>");
    for ( var j=2; j <= 9; j++ ) {  // <-- inner loop
      document.write(i + " x " + j + " = " + i * j + "<br>");
    }
  }

 

while - loops


while loop is another commonly used loops after for-loop. It keeps repeating everything inside the brackets as long as the expression inside the parenthesis is true. Consider the following code, which generates the drop-down menu with the list of years as we did in earlier sections:







document.write('<select name="year">');
  var i = 1900;
  while ( i != 2005 ) {
   document.write('<option value=' + i + '>' + i + '</option>');
   i++;
  }
  document.write('</select>');

 

Loop control with break


Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decided when to exit the loop. Although you will rarely be using this sort of loops, it is good to know about break keyword.

break can be used to terminate the loop from within the loop expression:

01 
02 
03 
04 
05 
06 
07 
08 
09 
10 

document.write('<select name="year">');
  var i = 1900;
  while ( 1 ) {
   if ( i == 2005 ) {
    break;
   }
   document.write('<option value=' + i + '>' + i + '</option>');
   i++;
  }
  document.write('</select>');


Notice the way the loop is initialized, with while ( 1 ). Since the condition inside brackets, 1, is always true, the only way this loop can be terminated is through the break statement.

JavaScript Variables

While programming with JavaScript, you will constantly be working with two things, data and statements to perform operations on these data. JavaScript, just like any other programming language, uses variables to store data in. You can create new variable with var keyword.

To extend our first example, let's store the text to be printed inside a variable instead of passing the text itself to document.write() as we did above:


var text = "Hello from JavaScript";
alert(text)


Effect of the above example is identical with the first one; both print text Hello from JavaScript to the screen. Notice how we're declaring a variable text. Also notice how we're printing the variable; no more double quotes around the variable, which tells the JavaScript interpreter that it is a special token.

Note, that you don't have to assign a value to a variable at declaration. You can simply create a variable with undefined value, and only then fill it in:



var text;
  // after some time...
  text = "Hello from JavaScript";


We have just used all two components of a programming language - data and statement. Variable text was data, and document.write(text) was a statement used to output data to the screen. Although our example is still very basic, you will be using both of these components in even more comprehensive projects.

String Concatination


Speaking of our previous example, let's say we want to split the greeting into two separate variables. The first variable will hold Hello from, and the second one will hold JavaScript. In the end we will concatenate these two strings into a single solid string. String concatenation is an act of adding one string to another.

You can concatenate strings in JavaScript with + (plus) operator.



var greeting = "Hello from";
  var js       = "JavaScript";
  document.write(greeting + js);


When we put the above example in our HTML pages, the result is Hello fromJavaScript. There is a space missing after from and JavaScript. To fix this problem we need to put a single space between greeting and js variables. Revised version looks like this:



var greeting = "Hello from";
  var js       = "JavaScript";
  document.write(greeting + " " + js);


Notice how we are adding greeting, " " and js with the help of + (plus) operator.

Arrays


So far we managed to store a single data value in a variable. It works fine as long as the number of variables are manageable. What if we need to store the names of all the US states?

Array is another type of variable in JavaScript designed for holding multiple values. You declare a variable to be of Array type with the following syntax:

var states = new Array(50);


The above code is creating a variable called states, which will hold an array value. 50 inside parenthesis denotes the number of elements the array will hold. In our case it holds names of 50 states.

We can now start assigning state names for this array. You can reference a single element of an array using [] operator. Name of the variable should be left of the bracket, and a non-negative integer value indicating the position of the element should be inside brackets:






states[0]  = "Alaska";
  states[1]  = "Alabama";
  states[2]  = "Arkansas";
  states[3]  = "Arizona";
  ....
  states[49] = "
Wyoming";



Notice that index of the elements of an array starts at 0 (zero), not 1. So 50th element of the array will have an index of 49. You can use states.length() notation to find out actual length of the array. We will cover this in more details in our LOOPS IN JAVASCRIPT section later in this article.