[On the previous page ],[On the main page]

JavaScript. Expressions, base operators.

The general items of information

    For what, actually, was necessary JavaScript. JavaScript is developed in common by companies Sun Microsystems and Netscape. Recently popularity JS very much has increased as a result of issue of the newest browsers supporting the given language.
    Some developers of the Web-applications use Java Applets. Yes, certainly, there are very beautiful things. Now look at those sites, which offer applets. You can notice, that the authors of such pages them do not use. As to me, you will not find here applets. The reason that there are applets not correctly written. The applets are loaded into memory of the computer and remain there up to rebot of the computer. And if there were global variable, changed properties, methods of standard objects? I on a place of the developers of browsers would build the warning! " Cautiously applets! " It was deviation, that you did not confuse completely different languages: Java and JavaScript.
    

So, we shall begin:
    Scripts can be in any place of the HTML-document. However tags HTML it is impossible to place inside the JS-program. JS the program is located between tags <script> ... </script>, the exception is made by operations of processing of events.
    Having met tag <script>, the browser analyzes each line of the document until will be achieved tag </script>. After that the check of the program on presence of mistakes and transformation JS of the program in a format is made which is then carried out on the computer of the user.
    The body JS of the program can be placed in the container <head>... </head>, As it is read out at loading HTML of the document by one of first. Theoretically text of the program is possible to place in any place HTML of the document, though better it to make in front of the container <body>... </body>, i.e. in heading of the document. The final choice will be made by you.

   Syntax of the tag:
     <script language="JavaScript">
      [The text of the program]
  </script>

It is necessary to mean, that the word "JavaScript" enters the name with observance of the register of symbols.

Expressions of language JavaScript.

    The expression is a combination variable, operators and methods returning certain value.

Expressions of a condition.

    The expressions of a condition are used for comparison one variable with others, and also with constants or values returned various expressions. In language JS there is an operator of comparison ?, having syntax:

(Expression of a condition) ? operators_1 : operators_2

    If the expression of a condition is true - are carried out operators_1, In the other case - operators_1. It is possible also to give values variable. For example, operator:

      type_time = (hour >= 12) ? "PM" : "AM" gives string value "PM" variable type_time, if the value variable hour is more or equally 12; otherwise is given "AM". The operator ? Actually is the reduced variant of the operator if . . . else. The previous example can be written down so:

  if (hour >= 12)
    type_time="PM";
       else
        type_time="AM";

Operations of giving

     In language JS there are some variants of giving:

=

Direct giving of value to the left operand

+=

Puts values of the left and right operands and gives result to the left operand

+

Puts values of the left and right operands and gives result to the left operand

++

Increases value of the left operand (right operand can be absent)

-=

Subtracts values of the left and right operands and gives result to the left operand

-

Subtracts values of the left and right operands and gives result to the left operand

--

Reduces value of the left operand (right operand can be absent)

*

Multiplies values of the left and right operands and gives result to the left operand

*=

Multiplies values of the left and right operands and gives result to the left operand

/

Divides values left on the right operands and gives result to the left operand

/=

Divides values left on the right operands and gives result to the left operand


So, for example, it is possible to write down:
    nval *=10;
i.e. variable nval increases value in 10 times.
instead of:
   nval = nval * 10;

Operations of comparison:

= =

Equality

!=

Not equally

!

Logic denying

>=

It is more or equally

<=

Is less than or equal

>

It is more

<

It is less (whenever possible it is desirable to refrain from application of this expression)


    It is necessary to refuse expressions having a mark"<" whenever possible, how the given symbol can have and other value in the HTML-documents. In order to prevent mistakes, if the similar expression can serve as casual opening tag HTML:
  if mvar <h . . . . . . - can be interpreted as a beginning of heading HTML. tags HTML in JS the programs are invalid.

Logic operations

    For a designation of logic operation "AND" in language JS use two symbols (&&), and for a designation of logic operation "OR" - two symbols (||). These operations use only with logic values. For example:

bvar1 = true;
bvar2 = false;
bvar3 = true;

it is possible to write down expression:

bvar1 || bvar2
which will return valuetrue, how it is enough for the given expression of , that the value of one of operands was true. And expression:
bvar1 && bvar2
will return accordingly false how the operation logic "AND" is fulfilled.
    It is possible to write down and more complex expressions:

if ((bvar1 && bvar2) || bvar3) {
  function1();
}
     else {
   function2();
}
it is necessary to understand as:" To make active function function1(), if both variable bvar1 and bvar2 contain valuestrue, or even bvar3 contains true, differently to execute function function2 " For the given values the function will be carried out function1(), - bvar3 contains value true.

The base operators of language JavaScript

    The programs in language JS usually consist of program blocks or individual operators. The program blocks are groups of the operators, which consist in braces ({and}). Each operator, if it occupies a sole line, at the end of a line it is necessary to write (;), designating the termination of the operator. Each operator has own syntax. The syntax of the operator is a set corrected, which define obligatory and allowable for use in the given operator of value. Values, which presence is unessential, at the description of syntax it is accepted to conclude in square brackets, for example [value]. At non-observance corrected of syntax there will be a mistake of compilation.

The operators of the comments and notes

Syntax:
// The text of the comments
/* The text
of the comments
*/

    Accordingly first comment can have only one line, second a little. The comments are necessary extremely only for the explanatories or for temporary exception of some fragments of the program during debugging.

The operators of cycles

    In language JS there are operators for performance of iterations i.e. recurrence of the several operators.

Cycle "FOR"

Syntax:
for ([initialization of initial value;] [a condition;] [means of updating of the counter, step]) {
The program block
}

    The operator "For" allows repeatedly to carry out the operators in the JS-program. The operator "For" can be used for performance one or several operators. It is possible to not write braces, if the body of a cycle is contained only by one operator. All parameters of the operator For are unessential and are used for management of process of performance of a cycle. At application of all parameters each part needs to be separated by a point from a point (;).
The example of a conclusion in a window of a browser of horizontal lines, and everyone is longer previous:

<html>
<head>
<script language ="JavaScript">
function testloop() {
  var String1 = '<hr align="center" ;
   document.open();
for (var size = 5; size <= 100; size+=5)
   document.writeln(string1 + size + '%''>');
document.close();
}
</script>
</head>
<body>
<form>
<input type="button"
       value="Test the loop"
      onClick="testloop()">
</form>
</body>
</html>

    In the given example the program deduces in the document some horizontal lines - HTML tags (<HR>), - which size is increased with a step 5 (size + = 5) from 5 % up to 100 % of width of working area of a window of a browser. 20 iterations in total are formed. Variable String1 contains a line containing HTML-tag. In a cycle to this line the new value of width which have been written down in variable size is added. When the value by this variable will be equal 100, the cycle is finished. The braces in the given example are not necessary, because the body of a cycle is contained only by one operator. The HTML-document contains the button, which makes active function testloop () .

Cycle "WHILE"

Syntax:
while (condition) {
the program block
}

    Through the operator while it is possible to carry out one or several operators until the condition will be satisfied. If in a body of a cycle some operators are carried out, they are necessary for concluding in braces.
     Let's try to result an example of the program, which uses a cycle while . For example it is necessary to show on the screen the table of multiplication:

<html>
<head>
<script language ="JavaScript">
function ftable(inum) {
   var iloop = 1;
   document.writeln ("Table of multiplication for: <b>" + inum + "</b><hr><pre>");
/* Notice, that in parameters of function writeln are applied tags HTML is is allowable.
HTML-tags In the text of the JS-program are invalid.
*/
while (iloop <= 10) {
document.writeln(iloop + " x "+ inum + " = " + (iloop*inum));
iloop ++;
}
document.writeln("<</pre>");
}
ftable(prompt ("Enter number: ", 10));
</script>
</head>
</html>

    The table is created in function ftable () . The cycle while is carried out 10 times. The table is deduced through standard function of language JS writeln () . The method prompt () provides data input from the keyboard. In the given example the number for calculation of the table of multiplication from 1 up to 10 is entered.
    It was possible also to write the given example and in another way, using a cycle for :
for (var iloop=1; iloop <= 10; iloop ++) {
. . . . . . .
}

Exit from a cycle - operator "break"

Syntax:
break

    The operator break is used for an exit from any of a cycle, for example from a cycle for or while . The performance of a cycle stops in that point, in which this operator is placed, and the management is transferred to the following operator who is taking place directly after a cycle. Let's consider the following program:

<html>
<script language ="JavaScript">
function btest() {
var index = 1;
while (index <= 10) {
if (index = = 6)
break;
index ++;
}
//After improvement of the operator break the management passes here.
}
btest();
</script>
</html>

    In this example variable index the value 1 is given, and the cycle while should be carried out so long as value variable index less or equally 10 (index <= 10). However operator if checks performance of a condition index = = 6. If this condition is carried out, the cycle while is finished with the help of the operator break . In result the cycle while will be finished always after first six iterations, and the value variable index never will be equal 10.

Continuation of a cycle - operator "CONTINUE"

Syntax:
continue;

    The operator continue is used for interruption of performance of the block of the operators, which make a body of a cycle and continuation of a cycle in the following iteration. As against the operator break , the operator continue does not stop performance of a cycle, and on the contrary starts new iteration. If in a cycle while there is simply start of new iteration, in cycles for starts with the updated step.

Definition of function

Syntax:
function functionname (arg, . . .) {
The block of the operators
}

    The function is a block from one or several operators. The block carries out the certain actions, and then, probably, returns value. In language JS of procedure - the subroutines not returning of values, do not differ. All subroutines are described by functions, and if in function or from it the parameters - that after a name of function are not transferred the parentheses without parameters are put. If the function has some arguments, they are separated by a point. It is necessary also to remember, that in language JS inside one function there can not be other function. The braces designate a body of function. The function can not be executed until will be of the obvious manipulation to it.
    If it is necessary, that the function returned the certain value, the unessential operator "return", thus having specified in it is necessary to use expression, which value it is required to return.

Return of value by functions - operator "return"

Syntax:
return (value);
return value;

    The operator return finishes performance of function and returns value of the given expression. The brackets in this operator can be not used. The operator return can be absent in function, if the function does not return value.
    The operator return is usually used for return of one value, however it(he) can be applied to return of array:

function retarray() {
var sarray = new Object();
sarray[1] = "Java";
sarray[2] = "Script";
return (sarray);
}
The manipulation to arguments of function through a array argunents [] ( is not supported in the old versions of browsers)
    The list of arguments transmitted to the current function is stored in this array. So, first element of a array argunents [0] < /I > contains first argunent of function, < I > argunents [1] - second etc. Total of arguments is stored in property arguments.length . A small example, which deduces on the screen all arguments transmitted functions:
function showargs() {
   arglist = "";
   for (var n=0; n <= arguments.length; n++) {
       arglist += n +"." + arguments[n] + "\n";
}
alert(arglist);
}

    Let's result an example including function showargs ().
Pay attention, that the function is caused all with two arguments, though in the description of function three are given. In this case last argument is defined as value null. In function showargs () the line of arguments is created which then is deduced on the screen with the help of a method alert () .

<html>
<script language ="JavaScript">
<!--
function showargs(a, b, c) {
arglist = "";
   for (var n=0; n <= arguments.length; n++) {
     arglist += n +"." + arguments[n] + "\n";
}
alert(arglist);
}
showargs("java","script")
//-->
</script>
</html>

The conditional operators - " if... else "

Syntax:
if (condition); {
  The program block 1
} [ else { The program block 2 }]

    The operator if... else is a conditional operator, which provides performance one or several operators, depending on, whether the conditions are satisfied. The part condition of the operator if is expression, at which validity the operators of language in the first program block are carried out. The program block should be made in braces, however if one operator is used only, it is possible brackets to not put. The unessential part else provides performance of the operators of the second block, in case the condition condition of the operator if is false. The operators if it is possible to put each other. Let's result an example. Well we shall change for example colour of a background depending on system time: first half of hour let will be dark blue, second - black:

<html>
<head>
<script language ="JavaScript">
<!--
today = new date();
minutes = today.getMinutes();
if (minutes >=0 && minutes <= 30)
   document.write("

It is written white on dark blue");
     else
       document.write("

It is written red on black");
//-->
</script>
</body>
</html>

The operator "?"

Syntax:
(expression) ? trueStatements ? falseStatements; {
where expression - expression in language JS, the result of which performance is equal or true , or false . Instead of trueStatements and falseStatements one or several operators JS are substituted which are carried out depending on result of calculation of expression expression . The operators trueStatements are carried out, if the expression is true, and falseStatements - if it is false. The operator ? is the reduced variant of recording of the operator if... else . I mention it once again that it works a little bit faster than operator if . In the given below example we shall change colour of a background depending on value of seconds in the current system time:

<html>
<head>
<script language ="JavaScript">
<!--
var today = new date();
var secs = today.getSeconds();
(secs >=0 && secs <= 30) ?
   document.write("

It is written white on dark blue") :
   document.write("

It is written red on black");
//-->
</script>
</body>
</html>

The enclosed operators "?"

    For check of several conditions the operators ? it is possible to put each other. As an example we shall consider the program, in which we shall check more values. For example we shall make the program, which will check value of seconds, if in an interval from 0 up to 30, - the colour of a background becomes light-blue. When the value is more 30, the program checks, in what interval there is a value of seconds - from 31 up to 50 whether or not. If the result will be true, the colour of a background will change on black, otherwise background becomes beige:

<html>
<head>
<script language ="JavaScript">
<!--
var today = new date();
var secs = today.getSeconds();
(secs >=0 && secs <= 30) ?
   document.write("

It is written white on dark blue") :
       (secs >=31 && secs <= 50) ?
   document.write("

It is written red on black"):
   document.write("

It is written white on beige");
//-->
</script>
</body>
</html>

Creation variable

    Variable are created or through the operator "var", or at direct assignment of values with the help of the operator of giving (=).

The operator "var"

Syntax:
var variablename [= value | expression];

    The operator var creates new variable with a name variablename . The scope by this variable will be either local, or global depending on, where is created variable. Actually at creation the variable operator var is possible to not write, however in this case in the right part of the operator of giving the value should be specified. Variable, created inside function will be inaccessible outside function, that is variable will be local.

The reference to the current object - operator "this"

Syntax:
this[.property]

    The operator this is internal property of language JavaScript. The value this represents the current object having standard properties, such as name , length and value . The operator this it is impossible to use outside of a scope of function or call of function. When the argument property is not used, with the help of the operator this the current object is transferred. However at the reference to object, as a rule, it is necessary to specify its certain property.
    The operator this is applied for " of elimination of ambiguity " of object with the help of binding it in a scope of the current object, and also to make the program by more compact.
     For example, you can cause JS-function at processing event OnChange , contents, connected to change, of a field of input, using the operator this care of the current value of object:

<html>
<head>
<script language ="JavaScript">
<!--
function sendData (arg) {
alert( arg.name + "We change contents of a field of input.");
}
//-->
</script>
</head>
<body>
<form>
<table>
<tr>
<td> Name: </td>
<td><input name = "persname" type="text" > </td>
</tr>
<tr>
<td> E-mail: </td>
<td><input name = "email" type="text" > </td>
</tr>
</table>
</form>
</body>
</html>

    When the user changes contents of a field of input with a name persname , the function sendData () with argument this is caused. Value this in this case is the field of input determined in tag <input>. To take in the program any value connected to this object, it is necessary to specify the appropriate property. The property name is specified in the given example. Certainly, it would be possible at once to transfer in function argument this.name . To see contents of a textual field, it is necessary to use property this.value . If to not use the operator this , the function sendData () is necessary for changing as follows:

function sendData (arg) {
alert (document.forms[0].persname.name + "We change contents of a field of input.");
}

    Now function addresses to current document, referring on a field of input with a name persname . In this case it looks a little bit more difficultly, as for the reference to a field of input it is necessary to specify complete hierarchy of objects. If it is necessary to address not to the current document, and to the certain window, the recording of hierarchy of objects becomes even more difficult.
     Other example using property form is below given which concerns to the current object form to deduce on the screen all tags, describing elements of this form:

<html>
<head>
<script language ="JavaScript">
<!--
function seeElem (f) {
var elemlist = "";
for (var num=0; num < f.elements.length; num++) {
   elemlist += num + ". " + f.elements[num] + "\n";
}
alert(elemlist);
}
//-->
</script>
</head>
<body>
<form>
<table>
<tr>
<td> Name: </td>
<td><input name = "persname" type="text" > </td>
</tr>
<tr>
<td> E-mail: </td>
<td><input name = "email" type="text" > </td>
</tr>
</table>
<input type = "button"
     value = "Let's look tags of elements"
      onClick="seeElem(this.form)">
</form>
</body>
</html>

    The given program organizes a cycle, in which all elements of a file elements are looked through. In this cycle each element of the form is added to a resulting line, which then is formatted and is deduced on the screen through a window alert () . Pay attention, that in function seeAlert () the whole object form is transferred.

We create the current object - operator "with"

Syntax:
with (objname); {
     statements
}
    The operator with makes object designated as objname , by the current object for the operators in the program block statements . The convenience of use of this operator consists that such recording allows to reduce volume of the text of the program. (< I > This you see is important for the web-applications < /I >) is below shown, as the operator with is applied to the built - in object Math of language JS.

with (Math) {
    document.writeln(PI);
}

    Such recording allows to avoid use prefix Math at the reference to constants of the given object. Let's consider an example, as the operator with with reference to object document is possible to use:

with (parent.frames [1].document) {
     writeln("We write here text");
     write("<hr>");
}

    In this case operator with relieves us of necessity to specify before methods writeln () and write () the document, to which the calls of these methods concern. In the given example the document containing frameworks is used.

     On it, perhaps, we shall finish consideration of the base operators, expressions and, at last, first acquaintance to language JavaScript. In Given clause the objects, methods, property and event were used which can to you while are not clear. In the following chapters methods, property of objects and events will be described practically everything, existing in language JavaScript objects, in more detail.
[On the previous page ],[On the main page]
BACK