JavaScript topics
JavaScript introductory concepts
JavaScript computer language
As you may already know, JavaScript is a computer language. A computer language consists of instructions that instruct the computer to perform a specific task. A task could be simple as validating the input on a form, for instance. The computer will perform this task based on the specific instructions (code) we write. In JavaScript, the code is normally processed (or executed) from the top line downward.
In everyday life, we use or process instructions to complete a task although it may not be always obvious. For instance, assume you have a task to visit this site, to perform this task you may follow these steps:
- turn ON your machine, if it is not ON
- connect to Internet
- open your browser
- type scriptbuzz.com in the browser’s address bar and press enter or click on a link that points to this site.
When writing code in a computer language such as JavaScript, you follow a similar procedure consisting of mini-steps that if completed, complete the main task. For example, if you wanted to show the user the total cost of the products for an online checkout, you may write your code that will:
- determine the cost of each item
- add and store (in computer’s memory) the cost of all items
- add tax, if any, to the above cost
- add shipping costs, if any, and add it to the above cost
- display the final cost to the user
When the written code in JavaScript is executed by a computer, it is converted to a machine code (or simply into binary numbers) because computers do not really understand JavaScript instructions. A special program called interpreter is responsible for “translating” JavaScript code to machine language each time the program (or the code) is run. Thus JavaScript is referred to as a interpreted language.
JavaScript history
Netscape released a scripting language called LiveScript in its early beta release of Navigator 2.0 in 1995. Netscape decided to rename the language as JavaScript to make it more sound like the hot Java programming language. Despite the fact these languages have similar names, they are two different programming languages.
First of all, JavaScript is easy to learn and use while Java is not. Furthermore, JavaScript is useful for simple tasks while Java is useful for complex tasks. Next, JavaScript does not require a developer’s kit but Java requires a Java Developer’s Kit (JDK) to create applets. The applet is a program that gets downloaded to a browser and then runs on the browser. Lastly, JavaScript can be directly inserted into HTML document but Java applets are separate files that must be complied (a format that a computer can execute) before they can be run. Table 1 provides a brief summary of difference between JavaScript and Java.
Table 1 Comparison of JavaScript and Java | |
---|---|
JavaScript | Java |
Easy to learn and use | Complicated to learn and use |
Useful for simple tasks | Useful for complex tasks |
No developer’s kit required | Requires Java Developer Kit to create applets |
JavaScript code is written directly in HTML and it does not require compiling | Java programs are saved in separate files and must be compiled before they can be run |
After Netscape introduced JavaScript in 1995, Microsoft introduced its own form of JavaScript called JScript for its browser: Internet Explorer. As time progressed, major browser vendors included support for different brands of JavaScript. Table 2 lists different versions of JavaScript and how Netscape and Internet Explorer support them.
Table 2 Different Versions of JavaScript | |
---|---|
JavaScript Version Number | Description |
JavaScript 1.0 | This is the first version of JavaScript and it is supported by Netscape 2.0 and Internet Explorer 3.0. |
JavaScript 1.1 | This version was introduced in Netscape 3.0 but only some parts were implemented in Internet Explorer 3.0. |
JavaScript 1.2 | Supported by both Netscape 4.0 and Internet Explorer 4.0. |
JavaScript 1.3 | Introduced in Netscape 4.06 and is supported by Internet Explorer 4.0 and above. |
Basics of JavaScript
If you already are not aware, with HTML you can only create static web pages. A static web page simply is a page whose content or layout won’t change. A dynamic page, on the other hand, is interactive and whose content changes according to the scripting instructions specified. To create a dynamic web page, you simply write a small program using a web programming language like Active Serer Pages, JavaScript, Perl, PHP, etc.
Server-side and client-side Scripting
The programs or scripting instruction that run on the server are referred to as server-side scripting. Active Server Pages is an example of a server-side technology which runs on a Windows server. The main advantage of using a server-side language is that the scripting code remains and runs on the server. One of the main disadvantages of using a server-side technology is that server slows down as many users access resources from the server. To combat that problem and other server-side scripting problems, use of client-side scripting is preferred.
JavaScript is a popular client-side scripting language. Client-side scripts run on the client’s (user’s) computer thus are more responsive to user’s actions than a server-side script as the data does not have to be sent over the internet.
JavaScript code is placed between the <script> and </script> tags. And, the JavaScript code inside the <script> tag can be placed directly in an HTML document. You may also link external JavaScript files to an HTML document. By doing that, you can share your JavaScript across multiple web pages.
Before you start writing JavaScript code, you should understand:
- Whitespace in JavaScript
- Statements in JavaScript
- Case sensitivity in JavaScript
- Code blocks in JavaScript
Whitespace in JavaScript
A whitespace character is an empty space (without any visual representation) on screen. Examples of whitespace characters include space characters, tabs, and line break characters. In JavaScript, use of excessive whitespace is ignored. For instance, the following JavaScript code,
a = b * d - c;
is equivalent to
a = b * d - c;
Thus both statements would be interpreted the same way. You might be asking be yourself why is whitespace important? Because whitespace is ignored in JavaScript, you can use it to benefit yourself by writing code that is more readable and understandable. The importance of whitespace though may not be realized in a smaller program. Suppose you had the following JavaScript code:
if (a > b) { document.write ("a is greater than b.");} else {document.write ("a is not greater than b"); }
As a programmer, the above code may be harder for you to follow but for the computer (specifically the interpreter) its more beneficial as much of the unnecessary space characters are eliminated. In the following code, however, we use reasonable amount of space for readability and understandability:
if (a > b)
{
document.write ("a is greater than b.");
}
else
{
document.write ("a is not greater than b");
}
From our above discussion, don’t assume JavaScript ignores all excessive whitespace. The exception is to our rule is use of whitespace in strings. In strings, whitespace is preserved, as in:
var AString = "Thisis a string";
Statements in JavaScript
A statement is an instruction that instructs a computer (JavaScript interpreter) to carry a specific action. For example,
document.write ("This is a JavaScript statement.");
instructs the computer to print “This is a JavaScript statement.” In JavaScript, statements are terminated with a semicolon or return statement. Because statements in JavaScript are ended with a semicolon, multiple statements can be grouped on one line, for example:
var x; x = 60; document.write (x);
In JavaScript, statements can also be terminated with a line break character, for example,
var x
x = 60
document.write (x)
The above three lines are treated as three separate statements as:
var x;
x = 60;
document.write (x);
To avoid ambiguity and any unintended results, use a semicolon to mark end of a statement instead of relying on an implicit semicolon insertion (or a linebreak character).
Case sensitivity in JavaScript
JavaScript is a case-sensitive scripting language. What that means is that the language considers capital letters as different from their lowercase counterparts. For example, if you declare a variable called totalCost in JavaScript, you have to use totalCost to refer to that variable not TotalCost, TOTALCOST, or some other combination.
In JavaScript the case sensitivity does not just apply to variable names but also to JavaScript keywords, event handlers, and object properties or methods. Keywords in JavaScript are all lowercase, for example, while, for, if, else, and so on. On the other hand, methods (properties) use “camel-back” naming convention (first word is in lowercase and each successive first letter of each word is capitalized), for example, toArray(), lastModified(), and so on.
Code blocks in JavaScript
A code block simply consists of grouped statements with curly braces ({ }). For example, statements grouped in a loop is referred to as a code block:

A code block can also be created with statements grouped in a condition:

Finally statements grouped in a function also create a code block:

Running JavaScript
The browser is responsible for running JavaScript. Thus the output from JavaScript is going to be more responsive as the data does not need to travel to or from server. A web browser runs JavaScript when a web page is downloaded or in response to an event.
JavaScript code can be placed either in an HTML file or an external file. So how do you decide where do you place your code? If your JavaScript code is small and cannot be used in any other web page, then, you should consider placing your code directly in the HTML document that uses it. If, on the other hand, your JavaScript is long and/or used very by many HTML documents, then, you should create a separate JavaScript file.
Because you can insert JavaScript code inside an HTML file, it needs to be distinguished from the rest of the text or code on the page. To separate your JavaScript commands from HTML commands or regular text on the page, insert your JavaScript code inside the opening <script> and closing </script> tag. For example,
<script language="JavaScript">
JavaScript commands
</script>
Because there are different client-side languages, we need to indicate to the browser which language we are using in our scripts. To indicate the scripting language, we added the language attribute to the <script> tag. Since we are using JavaScript, we set the language tag to JavaScript. If you omit the language tag from your <script> tag, the browser will assume that your code is written in JavaScript.
If you place your scripting code outside of the HTML page, you still use the <script> tag but then just add the src attribute. The value of src attribute tells the browser where your JavaScript code is located. For instance,
<script language="JavaScript" src="JavaScript/displayDate.js">
</script>
indicates that we are using JavaScript language and the JavaScript commands are located in a folder called JavaScript and a file called displayDate.js. A “.js” file extension indicates a JavaScript file.
Hiding JavaScript from older browser
Because not all browsers support JavaScript, we need a way to hide JavaScript from those browsers. If we do not JavaScript from those browsers, those browsers will treat JavaScript as page’s content and thus display that code on the web page. To avoid that problem, we can use the comment tags to hide the <script> tag. The following:
<script language="JavaScript">
<!--
JavaScript commands
-->
</script>
instructs browsers to ignore JavaScript if they don’t recognize JavaScript. How? Suppose we have an old browser that does not understand JavaScript. When this browser sees the above code, it ignores the first <script> tag, as it ignores any other tag that it does not recognize. The second line (<!–) starts an HTML comment. Text inside the comments is ignored by browsers and thus is not displayed on the webpage. To end a comment, we use –>. Thus any JavaScript code (line 3 above) placed inside the HTML document is ignored.
A browser that supports JavaScript will be able to execute the above code because it will ignore the HTML comments inside the <script> tag.
Sending output to a web page
JavaScript provide two methods for displaying text on a web page:
- document.write (“SomeText”);
- document.writeln (“SomeText”);
Note we used a semicolon above in each of the two statements. Any JavaScript statement (a complete JavaScript command) must end with a semicolon to mark the end of the statement.
If you have worked with a object-oriented language, you will immediately recognize that document is an object and both write and writeln are methods. The term “method” in context of object-oriented language means an action. As noted earlier, both of these actions print text. But what text do they print? Any text that is enclosed inside the double quotation marks (“”) or single quotation mark (”).
So the next question you may want to ask is what is the difference between these two methods? The “write” method prints the text to the browser without attaching a carriage return at the end of the text while the “writeln” method adds a carriage return to the end of text that you want to print to a web page.
Consider the following example that uses the “write” method
<script language="javascript">
document.write ("<pre>Line 1");
document.write ("Line 2</pre>");
</script>
to print the following:
<script language="javascript">
document.writeln ("<pre>Line 1");
document.writeln ("Line 2</pre>");
</script>
The output
Line 1Line 2
however is different if we use the “writeln” method:
Line 1 Line 2
We used the <pre> tag to show you the difference between the two methods. The “writeln” method, again, prints text with a carriage return at the end of the line. To show you that affect, we have to use the <pre> tag.
You can also use HTML tags to format text inside the write or writeln method. For instance,
<script language="javascript">
document.write ("Learn JavaScript from the <b>ScriptBuzz!</b>");
</script>
will print: Learn JavaScript from the ScriptBuzz!
Recall that the <b> tag in HTML is used for making some text bold.
Using escape codes/sequence — special characters
If you have used special characters in HTML, you may already know the purpose of using special characters. Like in HTML, special characters in JavaScript represent those characters that cannot be typed from the keyboard. For example, if you wanted to display a tab character in JavaScript, you cannot simply use the tab key. You will rather use the \t escape code (also called escape sequence). The backslash (“\”) in JavaScript has a special meaning because it is used with any special character you want to display in your web document. Table 1 lists the common escape sequences with the corresponding character that it represents. For instance, to display a new line, you will use the \n.
Table 1 common escape code / escape sequences in JavaScript | |
---|---|
Escape code / escape sequences | Character represented |
\b | backspace |
\f | form feed |
\n | new line |
\r | carriage return |
\t | tab (horizontal) |
\v | tab (vertical) |
\’ | single quote |
\” | double quote |
\\ | backslash |
As indicated above, the backslash has a special meaning in JavaScript. As such, how would you display a backslash in JavaScript? As table 1 shows, to display a backslash we will use \\. For instance,
<script language="javascript">
document.write ("Use \\n to start a new line.");
</script>
prints
Use \n to start a new line.
As another example, let’s say we want to print a double quotation mark as in:
Welcome to “JavaScript”!
To display the double quotation marks around the word JavaScript, you can use the escape sequence \”:
<script language="javascript">
document.write ("Welcome to \"JavaScript\"!");
</script>