Writing JavaScript Code - HTML

JavaScript follows a fairly basic syntax that can be outlined with a few simple rules:

  • With few exceptions, code lines should end with a semicolon (;). Notable exceptions to the semicolon rule are lines that end in a block delimiter ({ or }).
  • Blocks of code (usually under controls structures such as functions, if statements, and so on) should be enclosed in braces ({ and }).
  • Although not necessary, explicit declaration of variables is a good idea.
  • The use of functions to delimit code fragments is highly advised and increases the ability to execute those fragments independently from one another.

Data types and variables
Variables are storage containers where you can temporarily store values for later use. JavaScript, like most scripting languages, supports a wide range of variable types (integer, float, string, and so on) but incorporates very loose variable type checking. That means that JavaScript doesn’t care too much about what you store in a variable or how you use the variable’s value later in the script. JavaScript variable names are case-sensitive but can contain alphabetic or numeric characters. The following are all valid JavaScript variable names:


Although JavaScript doesn’t require that you declare variables before their use, declaring variables is a good programming habit to develop. To declare a variable in JavaScript, you use the var keyword. For example, each of the following lines declares a variable:

var name = “Hammond”;
var total;
var tax_rate = .065;

Variables are referenced in the script by their names—JavaScript doesn’t require any characters to prefix the variable names. For example, you can reference the variable named total by simply using the following:


Calculations and operators
JavaScript supports the usual range of operators for both arithmetic and string values. Tables the various operators supported by JavaScript.

Calculations and operatorsJava script Assignment operatorsJava script Comparission  operatorsLogical operators

Handling strings
Strings are assigned using the standard assignment operator (=). You can concatenate two strings together using the concatenate operator (+). For example, at the end of this code, the full_name variable will contain “Terri Moore”:

first_name = “Terri”;
last_name = “Moore”;
full_name = first_name + “ ” + last_name;

Control structures
JavaScript supports the following control structures:

  • if-else
  • while
  • for

The if-else structure
The if-else structure is used to conditionally execute lines of code, depending on a condition that is usually a comparison of values.

The if-else structure has the following syntax:

if ( condition ) {
...statements to execute if condition is true...
} else {
...statements to execute if condition is false...

Note:The else portion of the if-else structure is optional and can be omitted if you do not need to execute statements if the condition is false.
For example, consider the following code:

if ( state == “CO”) {
flower = “Columbine”;

This code sets the flower variable to “Columbine” if the state variable is “CO”. (The State flower of Colorado is the Columbine.)

The while structure
The while structure is used to execute lines of code over and over again while a certain condition is true.
The while structure has the following syntax:

while ( condition ) {
...lines to execute while condition is true...

For example, consider the following code:

while ( address.length < 20) {
address = address + “ ”;

This structure will spacefill (add spaces to the end of) the address variable until it is 20 characters in length. If it is already longer than 20 characters, the structure’s statements will be skipped altogether.

Tip:Always ensure that your while structures include a means to change the structure’s condition to false. Otherwise, you run the risk of creating an endless loop, where the while structure’s statements continuously repeat without end.

The for structure
The for structure is used to execute a block of code much like the while structure. The difference is that the for structure is tailored specifically for numerical loops, usually counting a specific number of loops.
The for structure has the following syntax:

for (assignment; condition; change; ) {
...statements to execute while condition is false...

The assignment, condition, and change blocks of the for structure work together to control the number of times the statements are executed.

  • The assignment block’s code is executed at the beginning of the loop and is executed only once.
  • The condition block provides a conditional statement. While this statement evaluates as true the loop continues to execute.
  • The change block’s code is executed at the end of each loop.

Typically, the blocks reference the same variable, similar to this example:

for ( x = 1; x <= 10; x++; ) {

In this case, the loop’s execution is as follows:

  • The variable x is set to 1 at the beginning of the loop.
  • The value of variable x is checked—if it is less than or equal to 10, the loop’s statements are executed.
  • At the end of each loop the variable x is incremented by one, and the loop is repeated.
  • In short, this structure would execute 10 times.

Note:The description provided here for the for structure is somewhat simplistic. The various blocks (referenced herein as assignment, condition, and change) can be quite complex and take various forms. The simplistic explanation here shows the most common use as a numeric counter and loop handler.

Break and continue
Two additional loop-related commands come in handy when using loops in JavaScript: break and continue. The break command ends the loop, and code execution continues after the loop structure.
The continue command ends the current iteration of the loop, and execution continues with the next iteration of the loop.

Functions are a means of grouping code fragments together into cohesive pieces. Typically, those pieces perform very specific tasks—receiving values to execute upon and returning values to indicate their success, failure, or result. There are essentially two types of functions, built-in JavaScript functions and user-defined functions.

Built-in functions
JavaScript has quite a few built-in functions to perform a variety of tasks. Augmenting the functions are a bunch of properties and methods that can be used with just about any object, from browser function to variable. The scope of built-in JavaScript functions, methods, and properties is too vast to adequately convey here.

User-defined functions
Like any other robust programming language, JavaScript allows for user-defined functions. User-defined functions allow you to better organize your code into discrete, reusable chunks.
User-defined functions have the following syntax:

function function_name (arguments) {
...code of function...
return value_to_return;

For example, the following function will spacefill any string passed to it to 25 characters and return the new string:

function spacefill (text) {
while ( text.length < 25 ) {
text = text + “ ”;
return text;

Elsewhere in your code you can call a function similar to the following:

address = spacefill(address);

This would cause the variable address to be spacefilled to 25 characters:

  • The spacefill function is called with the current value of address.
  • The spacefill function takes the value and assigns it to the local variable text.
  • The local variable text is spacefilled to 25 characters.
  • The local variable text (now spacefilled) is returned from the function.
  • The original calling assignment statement assigns the returned value to the address variable.

Note:The arguments passed to a function can be of any type. If multiple arguments are passed to the function, separate them with commas in both the calling statement and function definition, as shown in the following examples:

Calling statement:

spacefill(address, 25)

Function statement:

function spacefill (text, spaces)

Note that the number of arguments in the calling statement and in the function definition should match.
The variables used by the function for the arguments and any other variables declared and used by the function are considered local variables—they are inaccessible to code outside the function and exist only while the function is executing.

Using objects
One of the most powerful uses of JavaScript is in accessing document objects. You can use this ability to check document attributes, change document contents, and more.Most objects are accessed through the document’s object collection. The collection is referenced through a structure of tiered objects whose structure is similar to the following:


For example, the following statement references the address form field in the info form:


In order for this to work, the elements and subelements must be appropriately named in the document. For example, the form referenced in the preceding code would need name attributes for its elements:

<form name=“info” action=“handler.cgi” method=“post”>
<input type=“text” name=“address”>

To make use of objects, you also have to understand and use properties. Properties are attributes that an object has. In real life these would be attributes such as size, color, smell, and so on. In the DOM they are attributes such as value, length, and so on.

You reference an object’s properties by appending the property keyword to the object reference. For example, to reference the length of the address field, you would use the following:


Event Handling in JavaScript
You have seen the word events thrown around a lot in this part of the book so far. You’ll remember that an event is any action taken by the visitor sitting at the browser. An event can also be caused by the browser, such as when the page finishes loading. Every mouse movement, every click of the mouse, every keystroke can generate an event. As a developer, you must decide what kinds of actions you want to take based on events. Acting on events requires event handlers, which are discussed later in this chapter.

Table shows the major scriptable events.
Event Handling in JavaScript
Event Handling in JavaScript

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

HTML Topics