JavaScript Introduction

<< Click to Display Table of Contents >>

Current:  Script 

JavaScript Introduction

Previous pageReturn to chapter overviewNext page

Learn how to embed JavaScript scripts in dashboards by introducing JavaScript programming.

Object-oriented Concept

JavaScript is an object-oriented programming language (OPP), OOP language enables us to define our own objects and variable types. It provides multiple objects and methods, and the user-defined methods. It is believed that all contents in JavaScript almost are objects. 

Object. Objects are just special data. Objects have properties and methods.

Attributes. Attributes are characteristic values related to the object, such as name, length, and so on.

method. A method is an action (or a function that can be done) that an object can perform.

 

Basis of Script Language

The JavaScript language is similar to the common C++, Java, and other object-oriented language syntax. Create classes, include methods, and instantiate objects to create objects.

In JavaScript, when we use the function keyword to create a function, it is actually managed by the object in JavaScript, and we can dynamically set the object's properties and methods.

The following is a typical example:

// Define the constructor and set a property

function Person(name){

this.name = name;

}

// new Keyword instantiates an object

var Tom = new Person("Tom");

 

Notes and Naming

JavaScript uses double slashes "//" to start the single line note, and use "/**/" to add a multi-line note. 

// Single line note 

/* Multi-line

Note */

Semicolon ";" is the separator of statements.

var a_1 = 0;

JavaScript variable is used for saving values or expressions. A short name can be given to the variable, such as x, or a more descriptive name, such as length. JavaScript variable can also save the text value, for example carname="Volvo".

 

Rules of JavaScript variable name:

Variable is case sensitive (y and Y are two different variables) 

Variable must be start from letter or underline

The characters allowed used by variables include: letter, number and underline 

 

Declaration and Assignment 

JavaScript is a weak typed language. This does not mean that it has no data type, but the variable or JavaScript object attribute do not require a specified type of value to be allocated or it uses the same value all the time. One variable can be assigned to any value. The type of this variable is decided by the current assignment type. Therefore, declaration is needed before the use of local variable. Use key word "var" to declare a variable. 

var a_1 = "Hello";

If your assigned variable has yet to be declared, the variable will declare automatically. 

x=5;

carname="Volvo";

 

Type of Object and Action Scope

JavaScript is based on object. That means every value in JavaScript is an object.

// The following statements are of equal value

var c = a.concat(b);

c = a + b;

Generally, the object can be created and used are three types: native object, built-in object and host object.

JavaScript defines the native object as "ECMAScript realization provided object that is independent of host environment". In simple terms, native object is the type (reference type) defined by JavaScript. They include: Array, String and number, etc..

Built-in object is defined as "being provided by ECMAScript realization, being independent of all objects of host environment, and appearing when starting to execute ECMAScript program". That means the developer does not need to define the built-in object of instantiation, it has been instantiated.

JavaScript only defines two built-in object, that is Global and Math. 

a = parseInt(1234);// parseInt is the global object.

b = max(10, 12);// max is the object of Math.

All non-native objects are host objects which are provided by the host environment realized by ECMAScript. All BOM and DOM objects are host objects. 

Action scope refers to the applicable range of variables. Only one action scope exists in JavaScript - public action scope. All attributes and methods are public by default.

 

Number Object

Number object is the wrapper object of original numeric value.

var n = new Number(value);

var n = Number(value);

JavaScript will automatically convert the original numeric value to Number object. The method of allocating Number can be Number object or original numeric value. 

var n = 123;

Numbers can be decimal, octal or hexadecimal formats, the default is decimal. If it starts with "0x", it is hexadecimal format; if it starts with "0", it is octal format.

var n1 = 80;// it's decimal format by default

var n2 = 0xff;// hexadecimal format

var n3 = 012;// octal format 

The numeric type can use arithmetic signs +, *, /, -. It can also use increment/decrement operators ++, --.

 

Boolean Object

Boolean object refers two values: "true" or "false". When a value is used in a conditional statement, the undefined value will be returned as "false" result. If we want to determine whether a value is defined, the following statements can be used:

if(value) {

// Executing statement 

}

 

String Object

String object is used for processing text (character string). Character string generally uses single quotation mark or double quotation marks.

var s1 = "Hello";

var s2 ="Hello";

The character strings can be connected in serials by operators:

var s3 = s1 + "what?";

There are more common methods in character strings, including substring (), toLowerCase (), toUpperCase () and indexOf (), etc..

var s1 = "abc";

s1 = s1.toUpperCase(); // converted to ABC

var idx = s1.indexOf("B"); // return to 1

s1 = s1.substring(1, 2); // return to "B"

Supporting to the regular expression is built-in in character string. Match () method can search the specified value in character string, or find a match (matches) to one or multiple regular expressions. search () method is used for searching the specified sub-character string in character string, or search the matching sub-character string with regular expression.

var s2 = "abcdefg";

var reg = /bc/; // create the regular expression 

var idx = s2.search(reg); // return to "bc" location

 

Date Object

Date object deals with date and time. Date object will automatically save the current date and time as its original value.

var d1 = new Date();

The date object can be converted to a character string by adopting global function formatDate ():

var s1 = formatDate(d1, "yyyy-MM-dd"); // 2010-02-21

 

Array Object

Array object is used for saving multiple values in the single variable. Every item in the list is a numeric element, which is included in square brackets ([]). When creating a array, it will be initialized and use the specified value as its array element. The length is set as the number of specified element. 

var arr1 = ["beijing", "shanghai", "tianjin"];

Multi-dimensional array is an array of an array.

var arr2 = [[1, 2], [3, 4], [5, 6]];

 

Conditional Statements

Conditional statements in JavaScript is used for completing behaviors under different conditions. When you write codes, different behaviors need to be completed according to different conditions. Conditional statements can be used in codes to complete this task.

If statements

If...else statements 

If...else... if else statements 

if(x > 0) {

x = x + 1;

}

else {

x = x - 1;

}

 

for loop statements

When writing codes, usually you hope to execute the same code over and over again. We can use loop to complete this function, so the same code doesn't need to be wrote repeatedly. The loop in JavaScript is used for executing the codes for specified times (or when the specified condition is true). Use for loop under the operation time of script is confirmed.

for (variable = start value; variable <= end value; variable = variable + step value) {

Code needs to be executed 

}

while loop statement

The loop in JavaScript is used for executing the same code for specified times (or when the specified condition is true). while loop is used for executing the code when the specified condition is true. 

while (variable <= end value) {

Code needs to be executed 

}

There are two special statements can be used in loop: break and continue. break can stops the operation of loop, and continue to execute the following code of loop (if there is a code following the loop). continue command will stop the current loop, and continue the operation from the next value.

 

switch-case statements

Conditional statements in JavaScript is used for completing behaviors based on different conditions. If you wish to choose to execute one of several codes, you can use switch statement:

var theDay = new Date().getDay();

switch (theDay) {

case 5:

s = "Finally Friday";

break

case 6:

s = "Super Saturday";

break

case 0:

s = "Sleepy Sunday";

break

default:

s = "Work day";

}

(n) following switch can be expression, or can be (usually is) variable. Then the value in expression will be compared with number in case, if it matches certain case, the code following will be executed. break is for avoiding the code to be executed to the next line.

 

JavaScript Function

Function is driven by events, or the reusable code block when it is allocated for execution. Write the script as function, it can avoid to execute this script when loading the page.

Function includes some codes which can only be activated by events, or executed by calling functions.

You can call script (if the function insert an external .js file, then it can call from other page) in any position of a page.

function prod(a,b) { 

if(a > 0 && b > 0) {

var x = a * b; 

return x;

}

else { 

return 0;

}

}

 

Lifetime of JavaScript Variable

When you declare a variable in a function, you can only access this variable in his function. When exiting the function, this variable will be withdrawn. This variable is called as local variable. You can used the local variable of the same name in different functions because only the function of declared variable can distinguish every variable in it.

If you declares a variable out of a function, then all functions on the page can access this variable. The lifetime of these variables start from the declaration, and end at the close of page.