JavaScript Principles 101

This section covers the basics of JavaScript programming, its syntax, and how to work with data types, variables , and operators. This section is by no means a complete guide to JavaScript. For an in-depth JavaScript programming guide, several excellent books are available at your favorite bookstore that are dedicated to covering JavaScript at great length. This chapter gets you started so that you can at least become familiar with JavaScript, and it enables you to begin programming JavaScript in your Domino applications.

JavaScript General Uses

JavaScript offers many uses in Domino as well as on the Web. Here are a few of the more popular uses you will discover that work well using JavaScript.

Input Validation

When a user enters data on a form and saves it, the data entered by the user is often checked for errors before it is actually committed to file. This is commonly referred to as input validation. Notes programmers familiarly use the input-validation event of a field to see if the user has made any mistakes before saving the form. JavaScript offers yet another method of validating user input by way of the JS Header or the onBlur event for an element (field). Using the JS Header allows the developer to keep all the validations in one central area. This helps the developer at debug or code change time to quickly and easily find all the input-validation code instead of hunting around in all the form's fields. When the validation code is kept in each element separately, a more tedious development or redevelopment effort results. This is especially true during code changes, debugging, or user interface testing.

Object Manipulation

JavaScript has many built-in functions and predefined objects, such as button , file upload , password , radio button , text area , string , math , and date , to name a few. Developers can also extend JavaScript by creating their own objects. For example, if you need to build an object in JavaScript to represent the different types of cars available at a car rental company, you would have to define some basic information first:

This easily translates into JavaScript: rentalcar is the object, with its properties constructed as follows :

Rentalcar.make Rentalcar.model Rentalcar.seating Rentalcar.category Rentalcar.price

Its methods might be these:

Rentalcar.description() Rentalcar.locations()

This provides the developer with a much wider choice for defining his own objects, built-in or extended.

Handling Events

JavaScript is an event-driven language, meaning that when a button is selected, for example, JavaScript can be programmed to act on that event when it occurs. This is true for other events, such as when a form is saved or loaded, or when a mouse hovers over text on a form. A good example is the onClick event for a button object, which is used on a form to interact with the user when the button is selected. JavaScript allows even inexperienced developers to easily create event-driven elements in forms and pages in their application.

Communicating with Java and Plug-ins

Starting with browser versions 3.0 and greater, JavaScript can call preprogrammed Java applets and plug-ins. JavaScript's , , and tags are used for this.

Ingredients2: Recipes3: How to Make">

JavaScript Reserved Words

As with any language, certain words are reserved within the language itself. You cannot use these reserved words in functions, variables, methods, or object names . Table 16.5 lists all the JavaScript reserved words.

Table 16.5. JavaScript's Reserved Words

Abstract Else Long Synchronized
Boolean Extends Native This
Break False New Threadsafe
Byte Final Null Throw
Byvalue Finally Package Transient
Case Float Private True
Catch Goto Protected Try
Char Implements Public Var
Class Import Return Void
Const In Short While
Continue Instanceof Static With
Default Int Super  
Delete Interface Switch  

Working with Variables

Variables are flexible, temporary containers that store a value for the function being called. They can contain numbers or text, set to null , can be used as counters or flags, or can just pass arguments from one object or function to the next. Variables in JavaScript are no different from variables in any other programming language ”they must be declared and their values must be initialized .

Declaring

Declaring a variable is merely creating a container that holds a value. A variable's name can be any valid identifier, and its contents can be any valid expression. Variable names must begin with a letter, not a number or an underscore . Variables names cannot contain spaces and are case sensitive.

To name a variable, you must declare it like this:

candy="Candy Corn";

Alternatively, you can equally use the JavaScript var reserved word to declare the variable and initialize its value:

var candy="Candy Corn";

All local variables must be declared using the var reserved word. To make sure that it is declared as a global variable, declare it outside and at the top of your function:

var candy="Candy Corn"; //global variable function eatcandy(){ var candyjar="Jelly Beans"; //local variable }

A local variable is a variable that is declared inside a function. Its value can be used only by the function in which it is assigned. Each time the function is called, the variable is created. Likewise, when the function ends, the variable is nullified (emptied). A global variable is a variable that can be used between more than one function and whose value is shared. It is declared outside the function and, as good practice, is declared at the top of your function code.

Constants

A constant is value that holds constant or remains the same throughout the session in an application. It always is the same value. JavaScript doesn't really have any built-in constants other than true and false . Constants are typically defined at the beginning of a program and are usually capitalized:

MyConstant = "Red Hots"

By replacing the multiple instances of a value with a constant, it is much easier to make changes to the code at a later point in time by changing just one value instead of sifting through the code hunting for each instance where the variable used.

Data Types

JavaScript uses four standard data types: numbers, strings, Boolean values, and null values as shown in Table 16.6. JavaScript also has a NaN data type, or "Not a Number." Even though other languages have many more data types, JavaScript's four data types are sufficient enough to handle most needs. It is also helpful to know that JavaScript is not meant for very complex functions.

Table 16.6. JavaScript's Data Types

Data Type Example
Number Any number, such as 5 , 5.5 , or 23e5
String "Hello John! How's Anne?"
Boolean True or false
Null A value that equals nothing

Literals

A literal is a fixed value that literally provides a value to the function. For example, the number 2 is an example of a literal number value, the words "Sit on a stool!" make a literal string value, and true is a literal Boolean value.

For each data type, there are different ways to specify a literal.

Numbers

In JavaScript, the number data type allows numbers to be expressed as both integers and floating-point values.

Integers

Integers can be any positive or negative whole number. Numbers containing decimal points and fractions are not integers. The maximum integer size is based on the platform running the JavaScript application.

Integers are expressed in three different bases: base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Table 16.7 shows the definition of each base:

Table 16.7. JavaScript's Base Integer Types

Base Type Definition
Decimal ”base 10 Any whole number, as in 125 or 12.5
Octal ”base 8 Any integer with a leading zero, as in 0125
Hexadecimal ”base 16 Any integer with a leading 0x or 0X , as in 0x3F or 0XD52

Floating-Point Values

A floating-point value contains a positive or negative fractional component. A literal floating-point value contains a decimal integer and includes either a decimal point or an exponent indicator:

1E2 12.567 -12.5

Strings

A literal string value can contain zero or more characters enclosed in single or double quotes:

"Hi Roger! Can I buy you a drink?" '125' "" ''

Boolean

A literal Boolean value has only two possible values: true or false . Unlike other languages, in JavaScript, and 1 cannot be used as Boolean values. A Boolean value can be represented only by true or false .

Null

A null value returns just that, null . For example, when a Cancel button is selected on a form, the value returned will always be null . This is different from a string value of "" , which is actually a value of nothing.

NaN

Some functions in JavaScript have the ability to return a value that is Not a Number, or a NaN. Values can be tested using the isNaN() Boolean function, which returns true or false based on the argument passed to the function.

Expressions

JavaScript has several types of expressions in its language: assignment, arithmetic, logical, and string. If you ever paid attention in algebra class, now is the time to apply some of those techniques! Table 16.8 shows how each expression computes.

Table 16.8. JavaScript Expression Types

Assignment Assigns a value to a declared variable
Arithmetic Evaluates an expression to a number
Logical Evaluates an expression to a Boolean value ( true or false )
String Evaluates an expression to a string

In an expression, there is always a right operand and a left operand:

x = "My Expression"

The expression x is the left operand, = is the assignment operator, and "My Expression" is the right operand. JavaScript always interprets expressions from right to left. In this expression, "My Expression" is being assigned to the variable x .

Operators

Operators allow you to manipulate variables and objects inside JavaScript using arithmetic and comparisons to process data. Operators are the actual operands ” + , - , ! , = , and so on ”that are used to do the math and compare the data.

Assignments

To assign the value of an expression, assignment operators are used. The assignment operators in JavaScript are listed in Table 16.9.

Table 16.9. JavaScript Assignment Operators

= Assigns the value of the right operand to the left operand. Example: x = 125 .
+= Adds the left and right operands and assigns the result to the left operand. Example: x += y is the same as x = x + y .
-= Subtracts the right operand from the left operand, and assigns the result to the left operand. Example: x -= y is the same as x = x “ y .
*= Multiplies the two operands and assigns the result to the left operand. Example: x *= y is the same as x = x * y .
/= Divides the left operand by the right operand and assigns the value to the left operand. Example: x /= y is the same as x = x / y .
%= Divides the left operand by the right operand and assigns the remainder to the left operand. Example: x %= y is the same as x = x % y .

Arithmetic

JavaScript uses the standard binary arithmetic operators as well three unary operators, as listed in Table 16.10.

Table 16.10. JavaScript Arithmetic Operators

+ Addition x = y + z;
- Subtraction x = y - z;
* Multiplication x = y * z;
/ Division x = y / z;
++ Increment x = ++y; or x = y++;
-- Decrement x = --y; or x = y--;
(-) Unary negation x = -x

The standard binary arithmetic operators are the same as those found on a basic calculator. The unary operators are not. These operators are quite useful. Both the increment and decrement operators can be used in two different ways: before or after the operand. For example, ++x increments x by one and returns the result, whereas x++ returns x and then increments the value of x . Here's an expression to show you how this works:

x = 10; // x is assigned the value of 10. y = ++x; // x is incremented to 11 and assigned to y. z = x++; // z is assigned the value of 11 while the value of x is incremented to 12.

In the end, x = 12 , y = 11 , and z = 11 . Decrements are applied in the same exact way. The ++j expression is basically the same as j = j + 1 . Likewise, --j is the same as j = j - 1 .

Here is an example of some JavaScript code placed in the JS Header on a page in Domino Designer to show you how increment and decrement work. Figure 16.10 shows you what this looks like in Domino Designer:

Figure 16.10. The JS Header containing JavaScript increment and decrement code for the page.

Figure 16.11 shows you what this looks like in the browser.

Figure 16.11. The increment and decrement JavaScript code results in the browser.

Boolean

Boolean operators, also known as logical operators, include both binary and unary operators. They are used in conjunction with expressions that return Boolean or logical values. Here's how they work:

Operator Definition What It Returns
&& Logical AND

Returns true when both operands are true; otherwise , the expression returns false .

(3>1) && (4>2) returns true

(3>1) && (4<2) returns false .

  Logical OR

Returns true if either operand is true. It returns false when both operands are false.

(3>1) (4<1) returns true .

(3<1) (4<1) returns false .

! Logical NOT

Returns true if the operand is false, and returns false if the operand is true. This is a unary operator and is always a prefix of the operand. It always returns the opposite value of the expression.

!(3>1) returns false .

!(3<1) returns true .

Comparison

Comparison operators do just as the name implies: They compare two expressions and return a logical result. Two equals signs together ( == ) make up the equal comparison operator. When == is used between two expressions, you're really asking the question "Are the values of these two expressions equal?" Here's an example:

x = 5 y = 5 z = 20 x == y //this result is true. 5 does equal 5. y == z //this result is false. 5 does not equal 20.

Don't confuse == with = . The assignment operator = assigns a value to a variable, whereas the comparison operator == asks if the two operands are equal. Here are JavaScript's comparison operators:

Operator Definition What It Returns
== Equal Returns true if both of its operands are equal.
!= Not equal Returns true if both of its operands are not equal.
> Greater than Returns true if its left operand is greater in value than its right operand.
>= Greater than or equal to Returns true if its left operand is greater than or equal in value to its right operand.
< Less than Returns true if its left operand is less than its right operand.
<= Less than or equal to Returns true if its left operand is less than or equal to its right operand.

Bitwise

JavaScript gives you access to an integer's stored binary representation through bitwise operators. Simply put, at the lowest level an integer is represented by a bit. All integers in the binary number system are represented by 1 and 0. In the binary number system, the number 15 is represented as 1111 and the number 7 is 0111 . JavaScript actually reserves 32 bits per integer. So, the number 15 now becomes 00000000000000000000000000001111 and the number 7 now becomes 00000000000000000000000000000111 . When bitwise operators are used, JavaScript pairs each operand bit by bit and performs the operation on each pair. Here are the bitwise logical operators in JavaScript:

Operand What It Returns
AND (or & ) If both the operands are true, bitwise AND returns a 1 ; otherwise, it returns a .
OR (or ) If one of the operands is true, bitwise OR returns a 1 ; otherwise, it returns a when both operands are false.
XOR (or ^ ) If either operand is true, bitwise XOR returns a 1 ; it returns for any other combination.

Conditional

The conditional operator, ? , is based on the condition of an expression being true or false. The syntax of a conditional expression is as follows:

(condition) ? val1 : val2

The condition is any value that can be evaluated to equal a Boolean value. For example:

(day == "Friday") ? "Go to Louise's Pub after work!": "Go home and sleep!"

This expression means that if today is Friday, val1 is true , and you must go to the pub after work; otherwise, it's not Friday, val2 is true, and you must go home and sleep!

String

The string operator, + , is the same as the arithmetic operator, except with strings it acts as a concatenation operator. It allows you to concatenate strings together to make one large string:

var string1= "Roger, John, and Phil" var string2 = "drink a lot of beer." var result = string1 + " " + string2 document.write(result)

The result variable string value for this code is now equal to "Roger, John, and Phil drink a lot of beer."

Operator Precedence

When an expression uses more than one operator, JavaScript does not necessarily evaluate it from right to left or left to right. Each part of the expression is evaluated based on an order of predefined precedence for each operator. For example, in the following expression, there is no defined precedence:

x = y * z / 86400

In the previous example, the multiplication operator takes precedence over the division operator. To set the precedence for the division operator to be evaluated first, you would enclose the operands containing the division operator with parentheses:

x = y * (z / 86400)

This results in y being evaluated after the result of z divided by 86400 has been evaluated; then the value is finally assigned to x . If an expression has more than one of the same operator, JavaScript evaluates it from left to right.

Here's another example that shows you how JavaScript evaluates expressions:

Height = "The height of the bar stool is " + 1 + 2 + " feet."

This results in the variable height equal to this:

Height = "The height of the bar stool is 12 feet"

This is because JavaScript evaluates left to right when an expression contains more than one of the same operator. In this case, it was + . When parentheses are placed around 1 and 2 in the expression, it evaluates as this:

Height = "The height of the bar stool is " + (1 + 2) + " feet." The result equals "The height of the bar stool is 3 feet."

Table 16.11 lists the operator precedence in JavaScript from lowest to highest.

Table 16.11. JavaScript's Precedence of Operators

Comma ,
Assignment = , += , -= , *= , /= , %= , <<= , >>= , >>>= , &= , ^= , =
Conditional ? , :
Logical OR  
Logical AND &&
Bitwise OR  
Bitwise XOR ^
Bitwise AND &
Equality == , !=
Comparison < , <= , > , >=
Bitwise shift << , >> , >>>
Addition/subtraction + , -
Multiply/divide * , / , %
Negation/increment ! , ~ , - , ++ , --
Call, data structure ( , ) , [ , ]

Категории