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.
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
}
More Articles About Report APIs
Important KPIs for Business Budgeting - As mentioned above KPIs are crucial for tracking revenue, earnings, and productivity in any size of business. Companies can also modify KPIs to produce customized insights through the use of budgeting charts and software. Some of the KPIs found in budgeting dashboards include: 1. Net Profit Margin This shows how profitable a business is in relation to its sales. Often presented as a percentage, this KPI shows how much each dollar of revenue adds to the company's profit. This statistic can aid with project scalability in addition to demonstrating an organization's profitability...
KPIs for Management Consultants - Management consultants use various KPIs to keep track of their clients and ensure that they are meeting their objectives. Some of the KPIs that management consultants may use to track their clients include: Client satisfaction: This measures the satisfaction level of the client with the consultant's services. This can be measured through surveys or feedback sessions. Project delivery: This measures the ability of the consultant to deliver the project within the agreed timeline, budget, and scope...
Performance Management Process Tracking - There are several stages of the performance management process. First, the company needs to set its goals. Secondly, it needs to plan and execute the strategies for achieving those goals. Finally, it needs to evaluate the efficiency of the goals and the strategy it has used to get there. Key figures who set the goals and assign tasks to employees are the one who are responsible for performance management...
Role of an Operations Dashboard - The role of an operations dashboard is to provide a real-time, consolidated view of essential operational data and key performance indicators (KPIs) in a visually informative and easily accessible manner. Operations dashboards are used to monitor and manage various aspects of an organization's operations, processes, and performance. Here are the main roles and functions of an operations dashboard: Centralized Data Visualization: An operations dashboard serves as a centralized platform that brings together data from multiple sources and systems. It aggregates data from various departments, processes, and systems, providing a comprehensive and holistic view of the organization's operations...
Using a Marimekko Chart to Aggregate - A Marimekko chart, also known as a mosaic plot or a mekko chart, is a graphical representation of data that combines the features of a stacked bar chart and a 100% stacked bar chart. It is used to display the distribution of categorical data, typically in two dimensions, where the width of each column represents one category and the height of each column represents the relative frequency or proportion of another category. In a Marimekko chart, each column represents a category, and the width of the column corresponds to the proportion of data in that category. The height of each column is divided into segments, each representing a subcategory or subset of the data. The width of each segment is proportional to the proportion of data in that subcategory, and the length of each segment is proportional to the height of the column...