What is JScript ? | Basic of JScript

Basics on JScript

JScript is the Microsoft implementation of the ECMA 262 language specification. It is a full implementation, plus some enhancements that take advantage of capabilities of Microsoft Internet Explorer. This tutorial is intended to help you get started with JScript.

Easy to Use, Easy to Learn
JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than full-fledged object-oriented languages like C++ and Java, JScript is more than sufficiently powerful for its intended purposes.
JScript is not a cut-down version of any other language (it is only distantly and indirectly related to Java, for example), and it is not a simplification of anything. It is, however, limited. You cannot write standalone applications in it, for example, and it has little capability for reading or writing files. Moreover, JScript scripts can run only in the presence of an interpreter, either in a Web server or a Web browser.
JScript is a loosely typed language. That means you do not have to declare the data types of variables explicitly. Moreover, in many cases JScript performs conversions automatically when they are needed. For instance, if you try to add a number to an item that consists of text (a string), the number is converted to text.



Writing JScript Code 
Like many other programming languages, Microsoft JScript is written in text format, and is organized into statements, blocks consisting of related sets of statements, and comments. Within a statement you can use variables, immediate data such as strings and numbers, and expressions.

Statements
A  JScript code statement consists of one or more items and symbols on a line. A new line begins a new statement, but it is a good idea to terminate your statements explicitly. You can do this with the semicolon (;), which is the JScript termination character.
 

aBird = “Trenovision”;
var today = new Date();

 
A group of JScript statements that is surrounded by braces is called a block. Blocks of statements are used, for example, in functions and conditionals. In the following example, the first statement begins the definition of a function, which consists of a block of five statements. The last three statements, which are not surrounded by braces, are not a block and are not part of the function definition.
 

function convert(inches)  {
feet = inches / 12;  //  These five statements are in a block.
miles = feet / 5280;
nauticalMiles = feet / 6080;
cm = inches * 2.54;
meters = inches / 39.37;
}
km = meters / 1000;  //  These three statements are not in a block.
kradius = km;
mradius = miles;
 

Comments
A single-line JScript comment begins with a pair of forward slashes (//). A multiline comment begins with a forward slash and asterisk in combination (/*), and ends with the reverse (*/).
 

aGoodIdea = “Comment your code thoroughly.”;  //  This is a single-line comment.
/*
This is a multiline comment that explains the preceding code statement.
The statement assigns a value to the aGoodIdea variable. The value, which is contained
between the quote marks, is called a literal. A literal explicitly and directly contains
information; it does not refer to the information indirectly. (The quote marks are not
part of the literal.)
*/
//  This is another multiline comment, written as a series of single-line comments.
//  After the statement is executed, you can refer to the content of the aGoodIdea
//  variable by using its name, as in the next statement, in which a string literal is
//  appended to the aGoodIdea variable by concatenation to create a new variable.
var extendedIdea = aGoodIdea + ” You never know when you’ll have to figure out what it does.”;
 

 
Assignments and Equality
The equal sign (=) is used in JScript to indicate the action of assigning a value. That is, a JScript code statement could say

anInteger = 3;

It means “Assign the value 3 to the variable anInteger,” or “anInteger takes the value 3.” When you want to compare two values to find out whether they are equal, use a pair of equal signs (==). This is discussed in detail in Controlling Program Flow.
 
Expressions
A JScript expression is something that a person can read as a Boolean or numeric expression. Expressions contain symbol characters like “+” rather than words like “added to”. Any valid combination of values, variables, operators, and expressions constitutes an expression.

var anExpression = “3 * (4 / 5)”;
var aSecondExpression = “Math.PI * radius * 2”;
var aThirdExpression = aSecondExpression + “%” + anExpression;
var aFourthExpression = “(” + aSecondExpression + “) % (” + anExpression + “)”;

JScript Variables
Variables are used in Microsoft JScript to store values in your scripts. They are a way to retrieve and manipulate values using names. When used effectively then can help in understanding what a script does.
 
Declaring Variables
Although not required, it is considered good practice to declare variables before using them. You do this using the var statement. The only time you must use the var statement is when declaring variables that are local to a function. At all other times, using the var statement to declare variables before their use is a recommended practice.
The following code examples are of variable declaration:

var mim = “A man, a plan, a canal, Panama!”;  // The value stored in mim is of string type.
// The sentence in quotes, the value of which is assigned to mim, is a string literal.
var ror = 3;        // The value stored in ror has numeric type.
var nen = true;        // The value stored in nen has Boolean type.
var fif = 2.718281828        // The value stored in fif has numeric type.
 

Naming Variables
JScript is a case-sensitive language, so naming a variable myCounter is different from naming it MYCounter. In addition, variable names, which can be of any length, must follow certain rules:

  • The first character must be a letter (either uppercase or lowercase) or an underscore (_), or a dollar sign ($).
  • Subsequent characters can be letters, numbers, underscores, or dollar signs.
  • The variable name can’t be a reserved word

Some examples of valid variable names:

  • _pagecount
  • Part9
  • Number_Items

Some invalid variable names:

  • 99Balloons // Starts with a number.
  • Smith&Wesson // Ampersand (&) is not a valid character for variable names.

In instances in which you want to declare a variable and initialize it, but without giving it any particular value, you may assign it a special value, null.

var zaz = null;
var notalot = 3 * zaz;        // At this point, notalot becomes 0.
If you declare a variable without assigning any value to it, it exists but is undefined.
var godot;
var waitingFor = 1 * godot;  // Places the value NaN in waitingFor as godot is undefined.
You can declare a variable implicitly (without using var) by assigning a value to it. You cannot, however, use a variable that has never been declared at all. To do so generates an error at runtime.
lel = “”;  // The variable lel is declared implicitly.
var aMess = vyv + zez;  // Generates an error because vyv and zez don’t exist.
 

Coercion
As JScript is a loosely-typed language, variables in JScript technically have no fixed type. Instead, they have a type equivalent to the type of the value they contain. It is possible, under some circumstances, to force the automatic conversion (or coercion) of a variable or a piece of data into a different type. Numbers can easily be included in strings, but strings cannot be included directly in numbers, so explicit conversion functions, parseInt() and parseFloat(), are provided.

var theFrom = 1;
var theTo = 10;
var doWhat = “Count from “;
doWhat += theFrom + ” to ” + theTo + “.”;

After this code is executed, the doWhat variable contains “Count from 1 to 10.” The number data have been coerced into string form.

var nowWhat = 0;
nowWhat += 1 + “10”;  // In this case, because “10” is a string,
// the “+=” operator concatenates.

After this code is executed, the nowWhat variable contains “0110”. The following steps are followed to arrive at this result:

  1. Look at the types of 1 and “10”. The “10” is a string, the 1 is a number, so the number is coerced into a string.
  2. As the values on either side of the +operator are both strings, do a string concatenation. This results in “110”
  3. Look at the types of the values on either side of the +=. nowWhatcontains a number, and “110” is a string, so convert the number to a string.
  4. As there are now strings on either side of the += operator, do a string concatentation. This results in “0110”.
  5. Store this result in nowWhat.

var nowThen = 0;
nowThen += 1 + parseInt(“10”);        // In this case, “+=” performs addition.
After this code is executed, the nowThen variable contains the integer 11.

JScript Data Types 
Microsoft JScript has six types of data. The main types are numbers, strings, objects, and Booleans. The other two are null and undefined
String Data Type
Strings are delineated by single or double quotation marks. (Use single quotes to type strings that contain quotation marks.) A string is also an object in JScript, but it is a special case, with special properties,. The following are examples of strings:

“The cow jumped over the moon.”
‘”Avast, ye lubbers!” roared the technician.’
“42”

A string can contain zero or more unicode characters. When it contains zero, it is called a zero-length string (“”).
 



Number Data Type
JScript supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating-point number can contain either a decimal point, an “e” (uppercase or lowercase), which is used to represent “ten to the power of” in scientific notation, or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain number values that are special:

  • NaN, or not a Number
  • Positive Infinity
  • Negative Infinity
  • Positive 0
  • Negative 0

Integers can be represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal).
Octal integers are specified by a leading “0”, and can contain digits 0 through 7. If a number has a leading “0” but contains the digits “8” and/or “9”, it is a decimal number. A number that would otherwise be an octal number but contains the letter “e” (or “E”) generates an error.
Hexadecimal (“hex”) integers are specified by a leading “0x” (the “X” can be uppercase or lowercase) and can contain digits 0 through 9 and letters A through F (either uppercase or lowercase). The letter “e” is a permissible digit in hexadecimal notation and does not signify an exponential number. The letters A through F are used to represent, as single digits, the numbers that are 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16.
Octal and hexadecimal numbers can be negative, but cannot be fractional. A number that begins with a single “0” and contains a decimal point is a decimal floating-point number; if a number that begins with “0x” or “00” contains a decimal point, anything to the right of the decimal point is ignored.
Some example numbers:

.0001, 0.0001, 1e-4, 1.0e-4  // Four floating-point numbers, equivalent to each other.
3.45e2                       // A floating-point number, equivalent to 345.
42                           // An integer number.
0377                         // An octal integer, equivalent to 255.
00.0001                      // As octal numbers cannot have decimal parts, this is equivalent to 0.
0378                         // An integer, equivalent to 378.
0Xff                         // A hexadecimal integer, equivalent to 255.
0x37CF                       // A hexadecimal integer, equivalent to 14287.
0x3e7                        // A hexadecimal integer, equivalent to 999.
0x3.45e2                     // As hexadecimal numbers cannot have decimal parts, this is equivalent to 3.

Booleans
The possible Boolean values are true and false. These are special values, and are not usable as 1 and 0.

Note  In a comparison, any expression that evaluates to 0 is taken to be false, and any statement that evaluates to a number other than 0 is taken to be true. Thus the following expression evaluates to true:
(false == 0)

Undefined Data Type
A value that is undefined is simply a value given to a variable after it has been created, but before a value has been assigned to it.
Null Data Type
null value is one that has no value and means nothing.
 
JScript Operators
JScript has a full range of operators, including arithmetic, logical, bitwise, and assignment operators. There are also a few miscellaneous operators.
 

Computational Logical Bitwise Assignment Miscellaneous
Description Symbol Description Symbol Description Symbol Description Symbol Description Symbol
Unary negation Logical NOT ! Bitwise NOT ~ Assignment = delete Delete
Increment ++ Less than < Bitwise Left Shift << Compound Assignment OP= typeof Typeof
Decrement Greater than > Bitwise Right Shift >> void Void
Multiplication * Less than or equal to <= Unsigned Right Shift >>>
Division / Greater than or equal to >= Bitwise AND &
Modulo arithmetic % Equality == Bitwise XOR ^
Addition + Inequality != Bitwise OR |
Subtraction Logical AND &&
Logical OR ||
Conditional (trinary) ?:
Comma ,
Identity ===
Nonidentity !==

 
 
 
Operator Precedence
Operators in JScript are evaluated in a particular order. This order is known as the operator precedence. The following table lists the operators in highest to lowest precedence order. Operators in the same row are evaluated in left to right order.

Operator Description
. [] () Field access, array indexing, and function calls
++ — – ~ ! typeof new void delete Unary operators, return data type, object creation, undefined values
* / % Multiplication, division, modulo division
+ – + Addition, subtraction, string concatenation
<< >> >>> Bit shifting
< <= > >= Less than, less than or equal to, greater than, greater than or equal to
== != === !== Equality, inequality, identity, nonidentity
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Conditional
OP= Assignment, assignment with operation
, Multiple evaluation

Parentheses are used to alter the order of evaluation. The expression within parentheses is fully evaluated before its value is used in the remainder of the statement.
An operator with higher precedence is evaluated before one with lower precedence. For example:
z = 78 * (96 + 3 + 45)
There are five operators in this expression: =, *, (), +, and +. According to precedence, they are evaluated in the following order: (), *, +, +, =.

  1. Evaluation of the expression within the parentheses is first: There are two addition operators, and they have the same precedence: 96 and 3 are added together and 45 is added to that total, resulting in a value of 144.
  2. Multiplication is next: 78 and 144 are multiplied, resulting in a value of 10998.
  3. Assignment is last: 11232 is assigned into z.

Controlling Program Flow 
 
Fairly often, you need a script to do different things under different conditions. For example, you might write a script that checks the time every hour, and changes some parameter appropriately during the course of the day. You might write a script that can accept some sort of input, and act accordingly. Or you might write a script that repeats a specified action.
There are several kinds of conditions that you can test. All conditional tests in Microsoft JScript are Boolean, so the result of any test is either true or false. You can freely test values that are of Boolean, numeric, or string type.
JScript provides control structures for a range of possibilities. The simplest among these structures are the conditional statements.
 
Using Conditional Statements
 
JScript supports if and if…else conditional statements. In if statements a condition is tested, and if the condition meets the test, some JScript code you’ve written is executed. (In theif…else statement, different code is executed if the condition fails the test.) The simplest form of an if statement can be written entirely on one line, but multiline if and if…elsestatements are much more common.
The following examples demonstrate syntaxes you can use with if and if…else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to true, the statement or block of statements after the if is executed.
 

// The smash() function is defined elsewhere in the code.
if (newShip)
smash(champagneBottle,bow);  // Boolean test of whether newShip is true.
// In this example, the test fails unless both conditions are true.
if (rind.color == “deep yellow ” && rind.texture == “large and small wrinkles”)
{
theResponse = (“Is it a Crenshaw melon? <br> “);
}
// In this example, the test succeeds if either condition is true.
var theReaction = “”;
if ((lbsWeight > 15) || (lbsWeight > 45))
{
theReaction = (“Oh, what a cute kitty! <br>”);
}
else
theReaction = (“That’s one huge cat you’ve got there! <br>”);
 

Conditional Operator
JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition), and specifies two alternatives, one to be used if the condition is met and one if it is not. The alternatives are separated by a colon.

var hours = “”;
// Code specifying that hours contains either the contents of
// theHour, or theHour – 12.
hours += (theHour >= 12) ? ” PM” : ” AM”;

 

Tip   If you have several conditions to be tested together and you know that one is more likely to pass or fail than any of the others, depending on whether the tests are connected with OR (||) or AND (&&), you can speed execution of your script by putting that condition first in the conditional statement. That is, for example, if three conditions must all be true (using && operators) and the second test fails, the third condition is not tested. Similarly, if only one of several conditions must be true (using || operators), testing stops as soon as any one condition passes the test. This is particularly effective if the conditions to be tested involve execution of function calls or other code.
An example of the side effect of short-circuiting is that runsecond will not be executed in the following example if runfirst() returns 0 or false.
if ((runfirst() == 0) || (runsecond() == 0))
// some code

 
Using Repetition, or Loops
There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping. It is typically controlled by a test of some variable, the value of which is changed each time the loop is executed. Microsoft JScript supports many types of loop: for loops, for…in loops, while loops, do…while loops, and switch loops.
 

Using for Loops
The for statement specifies a counter variable, a test condition, and an action that updates the counter. Just before each time the loop is executed (this is called one pass or one iteration of the loop), the condition is tested. After the loop is executed, the counter variable is updated before the next iteration begins.
If the condition for looping is never met, the loop is never executed at all. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so take care when writing your loop conditions.
 

/*
The update expression (“icount++” in the following examples)
is executed at the end of the loop, after the block of statements that forms the
body of the loop is executed, and before the condition is tested.
*/
var howFar = 11;  // Sets a limit of 11 on the loop.
var sum = new Array(howFar);  // Creates an array called sum with 11 members, 0 through 10.
var theSum = 0;
sum[0] = 0;
for(var icount = 1; icount < howFar; icount++)  {        // Counts from 1 through 10 in this case.
theSum += icount;
sum[icount] = theSum;
}
var newSum = 0;
for(var icount = 1; icount > howFar; icount++)  {        // This isn’t executed at all.
newSum += icount;
}
var sum = 0;
for(var icount = 1; icount > 0; icount++)  {        // This is an infinite loop.
sum += icount;
}
 

Using for…in Loops
JScript provides a special kind of loop for stepping through all the properties of an object. The loop counter in a for…in loop steps through all indexes in the array. It is a string, not a number.

for (j in tagliatelleVerde)  // tagliatelleVerde is an object with several properties
{
// Various JScript code statements.
} 

Using while Loops
The while loop is very similar to a for loop. The difference is that a while loop does not have a built-in counter variable or update expression. If you already have some changing condition that is reflected in the value assigned to a variable, and you want to use it to control repetitive execution of a statement or block of statements, use a while loop.
var theMoments = “”;
var theCount = 42;        // Initialize the counter variable.
while (theCount >= 1)  {
if (theCount > 1)  {
theMoments = “Only ” + theCount + ” moments left!”;
}
else  {
theMoments = “Only one moment left!”;
}
theCount–;        // Update the counter variable.
}
theMoments = “BLASTOFF!”;
 
Using break and continue Statements
Microsoft JScript provides a statement to stop the execution of a loop. The break statement can be used to stop execution if some (presumably special) condition is met. The continuestatement can be used to jump immediately to the next iteration, skipping the rest of the code block but updating the counter variable as usual if the loop is a for or for…in loop.
var theComment = “”;
var theRemainder = 0;
var theEscape = 3;
var checkMe = 27;
for (kcount = 1; kcount <= 10; kcount++)
{
theRemainder = checkMe % kcount;
if (theRemainder == theEscape)
{
break;  // Exits from the loop at the first encounter with a remainder that equals the escape.
}
theComment = checkMe + ” divided by ” + kcount + ” leaves a remainder of  ” + theRemainder;
}
for (kcount = 1; kcount <= 10; kcount++)
{
theRemainder = checkMe % kcount;
if (theRemainder != theEscape)
{
continue;  // Selects only those remainders that equal the escape, ignoring all others.
}
// JScript code that uses the selected remainders.
}
var theMoments = “”;
var theCount = 42;  // The counter is initialized.
while (theCount >= 1)  {
// if (theCount < 10)  {  // Warning!
// This use of continue creates an infinite loop!
// continue;
// }
if (theCount > 1)  {
theMoments = “Only ” + theCount + ” moments left!”;
}
else  {
theMoments = “Only one moment left!”;
}
theCount–;  // The counter is updated.
}
theCount = “BLASTOFF!”;
Script Functions
Function
Microsoft JScript functions perform actions. They can also return results. Sometimes these are the results of calculations or comparisons.
Functions combine several operations under one name. This lets you streamline your code. You can write out a set of statements, name it, and then execute the entire set any time you want to, just by calling it and passing to it any information it needs.
JScript supports two kinds of functions: those that are built into the language, and those you create yourself.
 
Special Built-in Functions
The JScript language includes several built-in functions. Some of them let you handle expressions and special characters, and convert strings to numeric values.
For example, escape() and unescape() are used to convert characters that have special meanings in HTML code, characters that you cannot just put directly into text. For example, the angle brackets, “<” and “>”, delineate HTML tags.
The escape function takes as its argument any of these special characters, and returns the escape code for the character. Each escape code consists of a percent sign (%) followed by a two-digit number. The unescape function is the exact inverse. It takes as its argument a string consisting of a percent sign and a two-digit number, and returns a character.
Another useful built-in function is eval(), which evaluates any valid mathematical expression that is presented in string form. The eval() function takes one argument, the expression to be evaluated.
var anExpression = “6 * 9 % 7”;
var total = eval(anExpression);        // Assigns the value 5 to the variable total.
var yetAnotherExpression = “6 * (9 % 7)”;
total = eval(yetAnotherExpression)        // Assigns the value 12 to the variable total.
var totality = eval(“…surrounded by acres of clams.”);        // Generates an error.
 
JScript Objects 
Objects
In Microsoft JScript, objects are, essentially, collections of properties and methods. A method is a function that is a member of an object, and a property is a value or set of values (in the form of an array or object) that is a member of an object. JScript supports three kinds of objects: intrinsic objectsobjects you create, and browser objects, which are covered elsewhere.
 
 
Objects as Arrays
In JScript, objects and arrays are handled identically. You can refer to any of the members of an object (its properties and methods) either by name (using the name of the object, followed by a period, followed by the name of the property) or by its array subscript index. Subscript numbering in JScript begins with 0. For convenience, the subscript can also be referred to by its name.
Thus, a property can be referred to in several ways. All of the following statements are equivalent.
theWidth = spaghetti.width;
theWidth = spaghetti[3];  // [3] is the “width” index.
theWidth = spaghetti[“width”];
While it is possible to use brackets to refer to a property by its numeric index, it is not possible to use the dot (.) convention with index numbers. The following statement generates an error.
theWidth = spaghetti.3;
When an object has another object as a property, the naming convention extends in a straightforward way.
var init4 = toDoToday.shoppingList[3].substring(0,1);  // shoppingList, an array, is a property of toDoToday.
The fact that objects can have other objects as properties lets you generate arrays with more than one subscript, which are not directly supported. The following code creates a multiplication table for values from 0 times 0 through 16 times 16.
var multTable = new Array(17);  // Make the shell that will become the table.
for (var j = 0; j < multTable.length; j++)  {  // Prepare to fill it with rows.
var aRow = new Array(17);  // Create a row.
for (var i = 0; i < aRow.length; i++)  {  // Prepare to fill the row.
aRow[i] = (i + ” times ” + j + ” = ” + i*j);  // Make and place one value.
}
multTable[j] = aRow;  // Put the filled row into the table.
}
To refer to one of the elements of an array of this kind, use multiple sets of brackets.
var multiply3x7 = multTable[3][7];
The following statement generates an error.
var multiply3x7 = multTable[3, 7];

 
 
JScript Reserved Keywords

JScript has a number of reserved keywords. These words come in threetypes: JScript reserved keywords, future reserved words, and words to avoid.

JScript Keywords
Break False in this Void
continue For new true While
delete function null typeof With
else If return var

 

JScript Future Keywords
case debugger export Super
catch Default extends Switch
class Do finally throw
const Enum import try

The words to avoid are any that are already the names of intrinsic JScript objects or functions. Words like String or parseInt are included in this.
Using any of the keywords from the first two categories causes a compilation error when your script is first loaded. Using a reserved word from the third set can cause odd behavior problems if you attempt to use both your variable and the original entity of the same name in the same script. For example, the following script does not do quite what you think it should:
var String;
var text = new String(“This is a string object”);
In this case, you get an error saying that String is not an object. Many cases of using a pre-existing identifier aren’t this obvious.
Recursion
Recursion is an important programming technique. It’s used to have a function call itself from within itself. One handy example is the calculation of factorials. The factorials of 0 and 1 are both defined specifically to be 1. The factorials of larger numbers are calculated by multiplying 1 * 2 * …, incrementing by 1 until you reach the number for which you’re calculating the factorial.
Here’s the factorial function again, this time written in JScript code.
function factorial(aNumber)  {
aNumber = Math.floor(aNumber);  // If the number is not an integer, round it down.
if (aNumber < 0)  {  // If the number is less than zero, reject it.
return “not a defined quantity”;
}
if ((anumber == 0) || (anumber == 1))  {  // If the number is 0 or 1, its factorial is 1.
return 1;
}
else return (anumber * factorial(anumber – 1));  // Otherwise, recurse until done.
}
Special Characters 
JScript provides special characters that allow you to include in strings some characters you can’t type directly. Each of these characters begins with a backslash. The backslash is anescape character you use to inform the JScript interpreter that the next character is special.

Escape Sequence Character
\b Backspace
\f Form feed
\n Line feed (newline)
\r Carriage return
\t Horizontal tab (Ctrl-I)
\’ Single quotation mark
\” Double quotation mark
\\ Backslash

Notice that because the backslash itself is used as the escape character, you cannot directly type a one in your script. If you want to write a backslash, you must type two of them together (\\).
document.write(‘The image path is C:\\webstuff\\mypage\\gifs\\garden.gif.’);
document.write(‘The caption reads, “After the snow of \’97. Grandma\’s house is covered.”‘);
You can use these escape sequences to control formatting of text inside <PRE> and <XMP> tags and, to some extent, inside alert, prompt, and confirm message boxes.
Troubleshooting Your Scripts
There are places in any programming language where you can get caught if you are not careful, and every language has specific surprises in it. Take, for example, the null value: The one in Microsoft JScript behaves differently than the null value in the C or C++ languages.
Here are some of the trouble areas that that you may run into as you write JScript scripts.
Syntax Errors
Because syntax is much more rigid in programming languages than in natural languages, it is important to pay strict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be a string, you will run into trouble if you forget to enclose it in quotation marks when you type it.
Order of Script Interpretation
JScript interpretation is part of the your Web browser’s HTML parsing process. So, if you place a script inside the <HEAD> tag in a document, it is interpreted before any of the <BODY> tag is examined. If you have objects that are created in the <BODY> tag, they do not exist at the time the <HEAD> is being parsed, and cannot be manipulated by the script.
 
Automatic Type Coercion
JScript is a loosely typed language with automatic coercion. Consequently, despite the fact that values having different types are not equal, the expressions in the following example evaluate to true.
“100” == 100
false == 0
Operator Precedence
When a particular operation is performed during the evaluation of an expression has more to do with operator precedence than with the location of the expression. Thus, in the following example, multiplication is performed before subtraction, even though the subtraction appears first in the expression.
theRadius = aPerimeterPoint – theCenterpoint * theCorrectionFactor;
Using for…in Loops with Objects
When you step through the properties of an object with a for…in loop, you cannot necessarily predict or control the order in which the fields of the object are assigned to the loop counter variable. Moreover, the order may be different in different implementations of the language.
with Keyword
The with statement is convenient for addressing properties that already exist in a specified object, but cannot be used to add properties to an object. To create new properties in an object, you must refer to the object specifically.
this Keyword
Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannot ordinarily use this or similar keywords to refer to the currently executing function when that function is not an object definition. You can, if the function is to be assigned to an object as a method, use the this keyword within the function, to refer to the object.
Writing a Script That Writes a Script
The </SCRIPT> tag terminates the current script if the interpreter encounters it. To display “” itself, rewrite this as at least two strings, for example, “</SCR” and “IPT>”, which you can then concatenate together in the statement that writes them out.
 
Implicit Window References
Because more than one window can be open at a time, any window reference that is implicit is taken to point to the current window. For other windows, you must use an explicit reference.