JavaScript Syntax Basics

Number Type

JavaScript does not have an integer type and a float type. All numbers are treated as float by default.

 var total = 2 + 3;
 text = total; // this will convert the number to 5.0 

To force a number to be treated as an integer, use the toFixed() method of the number object and give a decimal point of zero:

 text = total.toFixed(0);
 // generates the string “5” 

A number constant is in decimal format by default, hexadecimal format if it starts with '0x', and octal format if it starts with '0'.

 decimal_number = 255 // -- Decimal is the default
 hex_number = 0xff
 fp_number = 2.456 // -- Floating point number 

Numerical computations are performed with the usual operators, +, *, /, -. The increment and decrement operators (++, --–) are also available.

Read how InetSoft was rated #3 for implementation in G2 Crowd's user survey-based index.

Boolean Type

A Boolean has a value of true or false.

 while(true) {
...
}

All undefined values are treated as false Boolean values when used in the context of a condition. You can check whether a value is defined by using the value in an if/else condition. For example:

if(parameter['start_time']) {
// action if 'start_time' is defined
... 
else {
// action if 'start_time' is not defined
...
} 

String Type

You can designate String constants using single or double quotes:

 var mystring = "InetSoft Technology Corp." 
mystring = 'InetSoft Technology Corp.' 

Concatenate strings with the plus operator:

 var str = 'Total: ' + total; 

If a value concatenated to a string is of a different type, it is converted to a string automatically. Strings have many methods, for example, substring(), toLowerCase(), toUpperCase() and indexOf().

 var str = 'abcd';
str = str.toUpperCase(); // converts to ABCD 
var bIdx = str.indexOf('B'); //return 1 
str = str.substring(1, 2); // return 'b' 

Strings have built-in support for regular expressions. You can find a regular expression in a string using the match() or search() method:

 str = 'this is a test of regular expression';
re = /test/; // create a regular expression 
var idx = str.search(re); // return the position of the regular expression 

Date Type

Date is represented as milliseconds since EPOC (Equipment Point of Connection). Creating a date object without specifying any parameters gives the current time:

 var now = new Date(); 

Convert a Date to a string using the global function formatDate().

str = formatDate(now, 'yyyy-MM-dd'); // 2002-02-21

The Date format uses the same syntax as the java.text.SimpleDateFormat class.

Arrays

An array is a list contained in a single variable. Each item in the list is known as an “element,” and the entire list is enclosed in square brackets ([]). When you create an array, it is initialized with the specified values as its elements. The following example creates the coffeelist array with three elements and a length of three:

var coffeelist = ["French Roast", "Columbian", "Kona"]; 

Multidimensional arrays are represented as an array of arrays. A two-dimensional array (rows and columns) may be created as follows:

var monthly_rain = [['Jan', 'Feb', 'Mar'],
[ 100,    10,   30  ],
[ 30,     10,   300 ],
[ 10,     10,   10  ]]; 

Conditionals

The if/else statement evaluates a Boolean expression to decide between two alternative actions.

if (x > 0) {
reg = event.region;
}
else {
reg = event.firstRegion;
} 

The “else if” construct allows you to test additional cases, similar to the Switch Statement.

 var day = CALC.weekdayname(CALC.today())
if (day == 'Thursday') {
Text1.text = 'Note: ' + day + ' hours are 10am-4pm.';
}
else if (day == 'Friday')
{ Text1.text = 'Note: ' + day + ' hours are 10am-12pm.';
}
else if (day == 'Sunday')
{ Text1.text = 'Note: ' + day + ' office closed.';
}
else { Text1.text = 'Note: ' + day + ' hours are 9am-5pm.';
} 

For Loop

A for loop instructs the server to repeat an action a specific number of times.

 //for (initial, condition-check, increment)
for (var j = 1; j < 10; j++) {
total = parseFloat(report['Table'].table[reg.y + j][3]); 
} 

The first expression in the loop (j = 1) initializes the loop variable. The second expression (j < 10) is a condition used to check when to terminate the loop (i.e., when the condition evaluates false). The third expression (j++) is the variable increment that is evaluated at the end of every iteration. The “j++” notation is the same as “j=j+1,” i.e., increment by one.

While Loop

The while loop iterates the contents of the loop until the loop condition becomes false.

 var n = 5;
Text1.text = "The factorial of " + n; var fact = 1;
// -- Compute n!, where n is a non-negative integer
while (n > 1) {
fact = fact * n;
n = n -1;
}
Text1.text += " is " + fact; 

Use the “break” command inside any loop to exit the loop, or use “continue” to skip to the next iteration.

Switch Statement

The switch statement is similar to the if/else if/else structure. However, rather than choosing a branch to execute based on a binary condition, the Switch chooses a branch (i.e., a case) based on a value.

var day = CALC.weekdayname(CALC.today())
switch(day) {
case 'Sunday':
Text1.text = 'Note: ' + day + ' office closed.';
break;
case 'Thursday':
case 'Friday':
case 'Saturday':
Text1.text = 'Note: ' + day + ' hours are 10am-12pm.';
break;
default:
Text1.text = 'Note: ' + day + ' hours are 9am-5pm.'
break;
}

Note that one or more values can be listed on each case (e.g., Thursday, Friday, Saturday). A 'break' statement should be included at the end of each case to terminate the switch statement.

The “default” label at the end serves as the catch-all case. If the switch value does not match any of the explicit case values, then the “default” block is executed.

Functions

See Also Script Library, for information on how to define new functions. JavaScript allows you to package a block of code into a function, which is a subprogram that performs a particular task. To execute the block of code, you simply “call” the function that contains the code. By packaging code into a function, you can easily this common code in multiple elements and reports, which makes script maintenance much easier.

JavaScript functions behave a little differently than functions in other languages:

• Input arguments do not require reference vs. value specification. (Primitive types are passed by value, whereas objects are passed by reference.)

• Input arguments do not require data type specification

• Return values are optional and do not require data type specification

 function max(a,b) // -- Two input arguments
{
if (a > b)
return(a); // -- Return a because it is larger
else
return(b); // -- Return b because it is larger
}