Javascript calculation operators. JavaScript operators. Simplified syntax for creating arrays and generators

💖 Do you like it? Share the link with your friends

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

Operators

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

operand1 operator operand2

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

operator operand operand operator 12; // 0.5 1 / 2 == 1.0 / 2.0; // this is true

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
Remainder (%) Binary operator. Returns the integer remainder of dividing the two operands. 12% 5 returns 2.
Increment (++) Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one. If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
Decrement (--) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
Unary negation (-) Unary operator. Returns the negation of its operand. If x is 3, then -x returns -3.
Unary plus (+) Unary operator. Attempts to convert the operand to a number, if it is not already. +"3" returns 3 .
+true returns 1.
Exponential operator (**) Calculates the base to the exponent power, that is, base exponent 2 ** 3 returns 8 .
10 ** -1 returns 0.1 .

Bitwise operators

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Var theDay = new Date(1995, 12, 17); if (theDay instanceof Date) ( // statements to execute )

Operator precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

Operator precedence
Operator type Individual operators
member .
call/create instance () new
negation/increment ! ~ - + ++ -- typeof void delete
multiply/divide * / %
addition/subtraction + -
bitwise shift << >> >>>
relational < <= >>= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluate and therefore resolve to a value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable.

JavaScript has the following expression categories:

Primary expressions

Basic keywords and general expressions in JavaScript.

this

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

This["propertyName"] this.propertyName

Suppose a function called validate validates an object"s value property, given the object and the high and low values:

Function validate(obj, lowval, hival) ( if ((obj.value< lowval) || (obj.value >hival)) console.log("Invalid Value!"); )

You could call validate in each form element"s onChange event handler, using this to pass it to the form element, as in the following example:

Enter a number between 18 and 99:

Grouping operator

The grouping operator() controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Var a = 1; var b = 2; var c = 3; // default precedence a + b * c // 7 // evaluated by default like this a + (b * c) // 7 // now overriding precedence // addition before multiplication (a + b) * c // 9 / / which is equivalent to a * c + b * c // 9

Left-hand-side expressions

Left values ​​are the destination of an assignment.

new

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

Var objectName = new objectType();

super

The super keyword is used to call functions on an object"s parent. It is useful with classes to call the parent constructor, for example.

Super(); // calls the parent constructor. super.functionOnParent();

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Var parts = ["shoulders", "knees"]; var lyrics = ["head", ...parts, "and", "toes"];

Similarly, the spread operator works with function calls:

Function f(x, y, z) ( ) var args = ; f(...args);

This chapter describes JavaScript expressions and operators, such as assignment, comparison, arithmetic, bitwise, logical, string, and various special operators.

Full and detailed list operators and expressions are also available in this tutorial.

Operators

JavaScript has the following types of operators. This subsection describes each type and contains information about their precedence over each other.

JavaScript supports binary and unary operators, as well as another special ternary operator, the conditional operator. A binary operation uses two operands, one before the operator and one after it:

operand1 operator operand2

For example: 3+4 or x*y.

A unary operation, on the other hand, uses one operand, before or after the operator:

operator operand operand operator

For example: x++ or ++x.

Assignment Operators

As a result of the assignment operation, the operand to the left of the assignment operator (the "=" sign) is set to the value that is taken from the right operand. The basic assignment operator is =, which assigns the value of the right operand to the operand on the left. Thus, the expression x = y means that x is assigned the value of y.

There are also compound assignment operators that are used to provide a shorthand representation of the operations described in the following table:

List of assignment operators
Name Shorthand operator Meaning
Assignment x = y x = y
Assignment with addition x += y x = x + y
Assignment with subtraction x -= y x = x - y
Assignment with multiplication x *= y x = x * y
Assignment with division x/=y x = x / y
Modulo assignment x %= y x = x % y
Left shift assignment x<<= y x = x<< y
Right shift assignment x >>= y x = x >> y
Unsigned right shift assignment x >>>= y x = x >>> y
Assignment with bitwise AND x &= y x = x & y
Assignment with bitwise XOR x^=y x = x^y
Assignment with bitwise OR x |= y x = x | y

Destructuring

For more complex assignments, JavaScript has destructuring syntax, an expression that allows you to retrieve data from arrays or objects using syntax that mirrors array constructors and object literals.

Var foo = ["one", "two", "three"]; // without destructuring var one = foo; var two = foo; var three = foo; // with destructuring var = foo;

Comparison Operators

You can use the delete operator to delete variables that are declared implicitly, but you cannot use it to delete variables that are declared with var .

After applying the delete operator, the element's property changes to undefined . The delete operator returns true if the operation is possible; the operator returns false if the operation cannot be performed.

X = 42; var y = 43; myobj = new Number(); myobj.h = 4; // create property h delete x; // returns true (you can delete a variable declared implicitly) delete y; // returns false (you cannot delete a variable declared using var) delete Math.PI; // returns false (built-in properties cannot be deleted) delete myobj.h; // returns true (you can delete custom properties) delete myobj; // returns true (you can delete an object declared implicitly)

Removing Array Elements

Removing an array element does not affect the length of the array. For example, if you remove a , the element a will remain a and a will become undefined.

When an array element is deleted using the delete operator, the value of that element is removed from the array. In the following example, the trees element is deleted using the delete operator. However, the trees element remains addressable and returns undefined .

Var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); delete trees; if (3 in trees) ( // condition is not met)

If you want an element to remain in the array but have an undefined value, then use the undefined keyword instead of the delete operator. The following example sets the trees element to undefined , but the element remains in the array:

Var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); trees = undefined; if (3 in trees) ( // this block of code is executed)

typeof operator

Use the operator instanceof when you need to confirm the type of an object during program execution. For example, when catching exceptions, you can create different programming transitions to handle exceptions depending on the type of exception being handled.

For example, the following code uses the instanceof operator to test whether theDay object is a Date object. Since theDay is indeed a Date object, the program executes the code contained in the if statement.

Var theDay = new Date(1995, 12, 17); if (theDay instanceof Date) ( // code to be executed )

Operator precedence

A priority operators determines the order in which they are executed when evaluating an expression. You can influence the precedence of operators using parentheses.

The table below describes operator precedence from highest to lowest.

Table 3.7 Operator priority
Operator type Operators
object property .
call, instantiate an object () new
negation, increment ! ~ - + ++ -- typeof void delete
multiplication, division * / %
addition, subtraction + -
bit shift << >> >>>
comparison, occurrence < <= >>= in instanceof
equality == != === !==
bit-and &
bit-exclusive-or ^
bit-or |
boolean-and &&
boolean-or ||
conditional (ternary) operator ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,

More detailed version this table containing links and Additional information for each operator, can be found in the JavaScript reference book.

Expressions

Expression is any valid block of code that returns a value.

Conceptually, there are two types of expressions: those that assign variable value, and those that calculate a value without assigning it.

The expression x = 7 is an example of the first type of expression. This expression uses operator= to assign variable x the value 7 . The expression itself also equals 7.

The code 3 + 4 is an example of the second type of expression. This expression uses operator"+" to add the numbers 3 and 4 without assigning the resulting result 7 to a variable.

All expressions in JavaScript are divided into the following categories:

Basic Expressions

Basic keywords and basic expressions in JavaScript.

This operator

Use the this keyword to point to the current object. In general, this points to the callable object that owns this method. Use this like this:

This["propertyName"] this.propertyName

Suppose the validate function checks the value property of some object; the object is specified, as well as the upper and lower bounds for the value of this property:

Function validate(obj, lowval, hival)( if ((obj.value< lowval) || (obj.value >hival)) alert("Invalid value!"); )

You can call the validate function on the handler onChange events for each form element, using this to point to the form element, as shown in the following example:

Enter a number from 18 to 99:

Grouping operator

The parenthesis grouping operator () controls the evaluation priority of expressions. For example, you can redefine the order - "multiply and divide before add and subtract" so that, for example, the addition is done before the multiplication:

Var a = 1; var b = 2; var c = 3; // usual order a + b * c // 7 // done as usual, so a + (b * c) // 7 // now change the order // addition before multiplication (a + b) * c // 9 // which is equivalent to the following a * c + b * c // 9

Simplified syntax for creating arrays and generators

Simplified syntax is an experimental JavaScript feature that may be added to future versions of ECMAScript. There are 2 versions of the syntax:

Simplified syntax for arrays. (for (x of y) y) Simplified syntax for generators.

Simplified syntaxes exist in many programming languages ​​and allow you to quickly assemble a new array based on an existing one. For example:

) i*i ]; // [ 1, 4, 9 ] var abc = [ "A", "B", "C" ]; ; // [ "a", "b", "c" ]

Left-handed expressions

Values ​​on the left are assigned to values ​​on the right.

new

You can use the new operator to instantiate an object of a custom type or one of the built-in objects. Use the new operator like this:

Var objectName = new objectType();

super

The keyword is used to call functions on the parent object. This is also useful with classes to call the parent's constructor, for example.

Super(); // calls the parent's constructor. super.functionOnParent();

Extension operator

The expansion operator allows an expression to expand in places with multiple arguments (for function calls) or multiple elements (for arrays).

Example: Today, if you have an array and want to create a new one with an existing part of the first one, then the literal array syntax is no longer enough and you must write imperative (no variants) code using a combination of push, splice, concat, etc. But with this operator the code becomes shorter:

Var parts = ["shoulder", "knees"]; var lyrics = ["head", ...parts, "and", "toes"];

The operator works in a similar way with function calls:

Function f(x, y, z) ( ) var args = ; f(...args);

Expressions in JavaScript are combinations operands And operators.

Operations in expressions are executed sequentially in accordance with the priority value (the higher the priority value, the higher it is). The returned result is not always of the same type as the type of data being processed. For example, comparison operations involve operands various types, but the returned result will always be a boolean type.

Rice. 1. Expression structure in JavaScript

Operands is the data processed by the JavaScript script. The operands can be either simple or complex data types, as well as other expressions.

Operators are language symbols that perform various operations with data. Operators can be written using punctuation characters or keywords.

Depending on the number of operands, the following types of operators are distinguished:
unary— one operand is involved in the operation;
binary— the operation involves two operands;
ternary— combines three operands.

The simplest form of expression is literal— something that evaluates to itself, for example, the number 100, the string "Hello world" . A variable can also be an expression, since it evaluates to the value assigned to it.

Expressions and Operators in JavaScript

1. Arithmetic operators

Arithmetic operators designed to perform mathematical operations, they operate on numeric operands (or variables that store numeric values), returning a numeric value as a result.

If one of the operands is a string, the JavaScript interpreter will try to convert it to a numeric type and then perform the appropriate operation. If type conversion is not possible, the result will be NaN (not a number).

Table 1. Arithmetic operators
Operator/Operation Description A priority
+ Addition Adds numeric operands. If one of the operands is a string, then the result of the expression is a string. 12
- Subtraction Subtracts the second operand from the first. 12
- Unary minus Converts a positive number to a negative number and vice versa. 14
* Multiplication Multiplies two operands. 13
/ Division Divides the first operand by the second. The result of division can be either an integer or a floating point number. 13
% Modulo division (division remainder) Calculates the remainder resulting from an integer division of the first operand by the second. Applies to both integers and floating point numbers. 13
var x = 5, y = 8, z; z = x + y; // return 13 z = x - y; // return -3 z = - y; // return -8 z = x * y; // return 40 z = x / y; // return 0.625 z = y % x; // return 3

2. Assignment operators

Assignment Operators are used to assign values ​​to variables. Combined operators allow you to store the original and subsequent values ​​in a single variable.

var a = 5; // assign the numeric value 5 to variable a var b = "hello"; // store the string hellow in variable b var m = n = z = 10; // assign the variables m, n, z the numerical value 10 x += 10; // equivalent to x = x + 10; x -= 10; // equivalent to x = x - 10; x *= 10; // equivalent to x = x * 10; x /= 10; // equivalent to x = x / 10; x %= 10; // equivalent to x = x % 10;

3. Increment and decrement operators

Operations increment and decrement are unary and increment and decrement the value of the operand by one. The operand can be a variable, an array element, or an object property. Most often, such operations are used to increment a counter in a loop.

var x = y = m = n = 5, z, s, k, l; z = ++x * 2; /* as a result of calculations will return the value z = 12, x = 6, i.e. the value of x is first increased by 1, and then the multiplication operation is performed */ s = y++ * 2; /* as a result of calculations will return the value s = 10, y = 6, i.e. First, the multiplication operation is performed, and then the value increased by 1 is stored in the variable y */ k = --m * 2; // return the value k = 8, m = 4 l = n-- * 2; // return the value l = 10, n = 4

4. Comparison operators

Comparison Operators are used to match operands, the result of the expression can be one of two values ​​- true or false . Operands can be not only numbers, but also strings, logical values ​​and objects. However, comparisons can only be performed on numbers and strings, so operands that are not numbers or strings are converted.

If both operands cannot be successfully converted to numbers or strings, the operators always return false .

If both operands are strings/numbers or can be converted to strings/numbers, they will be compared as strings/numbers.

If one operand is a string/converts to a string and the other is a number/converts to a number, then the operator will attempt to convert the string to a number and perform a number comparison. If the string is not a number, it is converted to NaN and the result of the comparison is false .

Most often, comparison operations are used when organizing branches in programs.

Table 4. Comparison operators
Operator/Operation Description A priority
== Equality Tests two values ​​for the same value, allowing type conversion. Returns true if the operands are the same, and false if they are different. 9
!= Inequality Returns true if the operands are not equal 9
=== Identity Tests two operands for "identity" using a strict definition of a match. Returns true if the operands are equal without type conversion. 9
!== Non-identity Performs identity verification. Returns true if the operands are not equal without type conversion. 9
> More Returns true if the first operand is greater than the second, otherwise returns false. 10
>= Greater than or equal to Returns true if the first operand is not less than the second, otherwise returns false. 10
Returns true if the first operand is less than the second, otherwise returns false. 10
Returns true if the first operand is not greater than the second, otherwise returns false. 10
5 == "5"; // return true 5 != -5.0; // return true 5 === "5"; // return false false === false; // return true 1 !== true; // return true 1 != true; // will return false since true is converted to 1 3 > -3; // return true 3 >= "4"; // return false

5. Logical operators

Logical operators allow you to combine conditions that return logical values. Most often used in an if conditional statement.

(2 < 3) && (3===3); // вернет true, так как выражения в обеих скобках дают true (x < 10 && x >0); // will return true if x is in the range from 0 to 10 !false; // return true

6. Bitwise operators

Bitwise operators operate on operands as a 32-bit sequence of ones and zeroes and return a numeric value indicating the result of the operation, written in decimal notation. Integer numbers are considered as operands; the fractional part of the operand is discarded. Bitwise operations can be used, for example, when encrypting data, working with flags, and delineating access rights.

Table 6. Bitwise operators
Operator/Operation Description A priority
& Bitwise AND If both bits are 1, then the resulting bit will be 1. Otherwise the result is 0. 8
| Bitwise OR If one of the operands contains a 1 at position, the result will also contain a 1 at that position, otherwise the result at that position will be 0. 6
^ Exclusive OR If one and only one value contains a 1 at any position, then the result will contain a 1 at that position, otherwise the result at that position will be 0. 7
~ Denial A bitwise negation operation is performed on the binary representation of the value of an expression. Any position containing a 1 in the original expression is replaced with a 0. Any position containing 0 in the original expression becomes 0 . Positive numbers start at 0, negative ones start at -1, so ~ n == -(n+1) . 14
The operator shifts the bits of the first operand to the left by the number of bit positions, established by the second operand. Zeros are used to fill positions on the right. Return a result of the same type as the left operand. 11
>> Bitwise shift right The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Digits shifted outside the range are removed. The most significant bit (32nd) is not changed to preserve the sign of the result. If the first operand is positive, the most significant bits of the result are filled with zeros; if the first operand is negative, the most significant bits of the result are filled with ones. Shifting a value to the right by one position is equivalent to dividing by 2 (discarding the remainder), and shifting to the right by two positions is equivalent to dividing by 4, etc. 11
>>> Bitwise right shift without sign The operator shifts the bits of the first operand to the right by the number of bit positions set by the second operand. Zeros are added to the left, regardless of the sign of the first operand. Digits shifted outside the range are removed. 11
var x = 9, y = 5, z = 2, s = -5, result; // 9 is equivalent to 1001, 5 is equivalent to 0101 result = x & y; // will return 1 (equivalent to 0001) result = x | y; // will return 13 (equivalent to 1101) result = x ^ y; // returns 12 (equivalent to 1100) result = ~ y; // will return -6 (equivalent to 1100) result = x<< y; // вернет 288 (эквивалентно 100100000) result = x >> z; // return 2 (equivalent to 10) result = s >>> z; // will return 1073741822 (equivalent to 1111111111111111111111111111110)

7. String operators

There are several operators that work with strings in special ways.

"1" + "10"; // return "110" "1" + 10; // returns "110" 2 + 5 + "colored pencils"; // returns "7 colored pencils" "Colored pencils" + 2 + 5; // returns "25 colored pencils" "1" > "10"; // return false "10"<= 10; // вернет true "СССР" == "ссср"; // вернет false x = "micro"; x+= "soft"; // вернет "microsoft"

8. Special operators

Table 8. Special operators
Operator/Operation Description A priority
. Accessing a property Accesses a property of an object. 15
,Multiple calculation Evaluates multiple independent expressions written on one line. 1
Array indexing Accesses array elements or object properties. 15
() Function call, grouping Groups operations or calls a function. 15
typeof Data type definition Unary operator, returns the data type of the operand. 14
instanceof Checking the type of an object The operator checks whether an object is an instance of a particular class. The left operand must be an object, the right operand must contain the name of the object class. The result will be true if the object on the left is an instance of the class on the right, false otherwise. 10
in Checking for the presence of a property The left operand must be a string and the right operand must be an array or object. If the left value is a property of an object, the result will be true . 10
new Creating an object The operator creates a new object with undefined properties, then calls the constructor function to initialize it (passing parameters). Can also be used to create an array. 1
delete Delete The operator allows you to remove a property from an object or an element from an array. Returns true if the deletion was successful, false otherwise. When an array element is deleted, its length does not change. 14
void Defining an expression without a return value Unary operator, discards the value of the operand and returns underfined . 14
?: Conditional expression operator The ternary operator allows you to organize simple branching. The expression involves three operands, the first must be a Boolean value or convert to one, and the second and third must be any values. If the first operand is true , then the conditional expression will take the value of the second operand; if false - then the third one. 3
document.write("hello world"); // displays the string hello world i = 0, j = 1; // stores values ​​in variables function1(10, 5); // function call function1 with parameters 10 and 5 var year = ; // creates an array with elements typeof (a:1); // return "object" var d = new Date(); // create a new object using the Date() constructor d instanceof Date; // return true var mycar = (make: "Honda", model: "Accord", year: 2005); "make" in mycar; // return true var obj = new Object(); // creates an empty object var food = ["milk", "bread", "meat", "olive oil", "cheese"]; delete food; // removes the fourth element from the array food x > 10 ? x * 2: x / 2; // returns x * 2 if x > 10, otherwise x / 2

9. Comments in JavaScript

Single-line comment: you must precede the comment text with the symbols // .

First, briefly about expressions in JavaScript.

JavaScript Expressions

JavaScript has statements and expressions.

Instructions do not return values.

Expressions Always return some values. When the interpreter sees an expression, it evaluates its value and replaces the expression with its value.

Expressions can be simple or compound. Simple expressions do not include other expressions.

Simple expressions include:

  1. Identifiers: someVar (variable name);
  2. Literals: "string" or 675 (number, or numeric literal);
  3. Some keywords like this ;

When the parser finds an identifier, it first needs to calculate its value, that is, for example, replace the name of a variable with its value.

The value of the literal will be the same as it is written in the script code.

JavaScript Operators and Complex Expressions

Operators are used to combine several simple expressions into one complex one.

Operators are:

  • Unary (one operand).
  • Binary (two operands).
  • Ternary operator? in JavaScript (three operands, there is only one ternary operator).

An operand is a simple expression to which an operator is applied.

For example, the arithmetic addition operator "+" is a binary operator. It sums the left and right operand and returns the sum.

Var digit = 4 + 7;

By the way, assignment occurs using the assignment operator "=". This operator evaluates the value of the right operand and assigns it to the left operand.

In JavaScript, unary plus has only one operand. Unary plus is not an arithmetic operator; it converts the operand to a number.

Var myVar = "7"; document.write(typeof(myVar) + "
"); // Prints string myVar = +myVar; document.write(typeof(myVar) + "
"); // Prints number in the document

At first, myVar contained the string "7", which is a literal of string type, not number. Using the unary plus operator, we converted a string literal to a numeric one.

Arithmetic operations

Arithmetic operations are well-known mathematical operations.

Perhaps the % (modulo) operator needs clarification. 9 is divided by 5 with a remainder of 4, and it is this remainder that this operator returns. It is also called modulo. When using integers, the result of this operator will also be an integer. When operating with floating point numbers, the result is a floating point number.

5.5 % 2.2 = 1.1

When performing arithmetic operations, it should be remembered that if performed incorrectly, they can lead to the following results:

  • NaN (Not a Number) is not a number.
  • Infinity - infinity.

Here's what dividing by zero does:

Var myVar = 0 / 0; document.write("The value of the variable: " + myVar + ", its type: " + typeof(myVar) + "
");

Comparison Operations

Comparison operators are used to compare expressions. An expression with a conditional operator returns a Boolean value - true or false (true / false).

Comparison operations can also be performed with strings; this will be discussed in another lesson. The only condition for a correct result is to match data of the same type. Otherwise, JavaScript will try to convert data from one type to another, and this is not always possible. To avoid errors, compare data of only one type.

Assignment Operators

The most obvious example of an assignment operator is the simple assignment (=). This operator (=) is used to assign a value to a variable.

But there are also a number of assignment operators that are shortcuts.

Logical operations

Boolean operations are often used with the if else construct in JS. It is through examples of this design that their work will be demonstrated. But first, a list of logical operators.

Now simple examples:

If (true && true) document.write("It works!
"); if (true || false) document.write("It works!
"); if (!false) document.write("It works!
");

Let's look at these examples:

The logical AND operator (&&) will return true if both operands are true.

The logical OR operator (||) will return true if at least one operand is true.

The logical NOT (!) operator takes one operand and reverses the true/false value.

Unary operators

Unary operators are operators with one operand. Here are a few such operators:

  • ++ - increase by 1 (increment). It can be prefix and postfix, more on that below.
  • -- - decrease by 1 (decrement). It can be prefix and postfix, more on that below.
  • + - unary plus.
  • - - unary minus.

Unary minus

A unary minus reverses the sign of an expression. For example, when you write -100 in a program, you are simply applying a unary minus to the number literal 100.

You need to understand exactly how the unary minus works - it returns the value of the operand with the opposite sign. Here is an example of how to correctly use a unary minus:

Var myVar = -100; document.write(-myVar + " - the unary minus worked, but the variable also = " + myVar + ".
"); myVar = -myVar; document.write("Now variable = " + myVar + ".
");

Let's give a meaningless example of a double unary minus. I think it will be useful for educational purposes:

Var myVar = -100; document.write(--myVar + " is an increment, not a double unary minus.
"); document.write("Now variable = " + myVar + ".
"); document.write(-(-myVar) + " and this is a double use of the unary minus.
");

Unary plus

The unary plus does not perform any mathematical operations. It casts a literal to a numeric type.

Var myVar = "78687"; document.write(typeof(myVar) + ".
"); myVar = +myVar; document.write(typeof(myVar) + ".
");

Increment and decrement

In programming, you often need to increase or decrease the value of a variable by one. There are unary operators for this:

  • ++ - increase by 1 (increment).
  • -- - decrease by 1 (decrement).

Unlike unary plus and minus, increment and decrement change the value of the variable when called.

Var myVar = 10; document.write(++myVar + ".
"); document.write(myVar + ".
");

Decrement (--) works the same way.

Now let's look at the prefix and postfix use of these operators.

  • ++myVar - prefix increase by 1.
  • myVar++ - postfix increment by 1.

The difference is this:

  • The prefix use of these operators first evaluates the value of the unary operator and then uses the result in an expression.
  • Postfix usage first evaluates the expression and then evaluates the unary operator (++ or -- ).

A simple example will help you understand this:

Var myVar = 10; document.write((++myVar + 5) + ".

"); var myVar = 10; document.write((myVar++ + 5) + ".
"); document.write("Variable = " + myVar + ".
");

Increment and decrement can only be used with variables; they cannot be used with numeric literals. Simply put, the ++7 code gave an error in the script.

Other operators

There are other operators in JavaScript:

  • Ternary (three operand) operator

var a = 10; var b = (a>1) ? 100:200; alert(b);

If the condition a>1 true, then the variable b assign value 100 , otherwise assign the value to variable b 200 .

Js task 3_4. Add code: 3 local variables are declared using keyword var. It is necessary to assign the value of the following ternary operator to the max variable: if a is greater than b, then we return a, otherwise we return b.
Code snippet:

if (a * b< 6) { result = "Мало"; } else { result = "Много"; }


Questions for self-control:

  1. What is the syntax of the ternary operator?
  2. How many arguments does the ternary operator have?

Switch operator in javascript - switch

The javascript switch statement is used to test a variable for multiple values:

Syntax:

switch (variable or expression) ( case option1: //..block of statements.. break case option2: //..block of statements.. break default: //..block of statements.. )

The value of a variable or expression is checked: in each case one of the values ​​is checked, if the value is suitable, one or another block of operators corresponding to this is executed case.

The block starting with the service word default can be omitted. The block statements will be executed if none of the listed values ​​are present in all case doesn't fit.

Important: The break statement is required after each considered variable value (after each case); if you do not use it, then all the statements below will be printed

Compare with the operator IF:

var a = 2; switch(a) ( case 0: // if (a === 0) case 1: // if (a === 0) alert("Zero or one"); // then print... break; case 2: // if (a === 2) alert("Two"); // then we display... break; default: // else alert("Many"); // otherwise we display... )

How to group several options?

To execute the same statements, it is possible to group several case. As in the example above:

Case 0: case 1: alert("Zero or one"); break; ...

When a = 0 and a = 1, the same statement is executed: alert("Zero or one");

Example 4: Prompt the user to enter a color. Output translation to English language entered color. For color "blue" And "blue" produce the same value.


✍ Solution:
  • Create a web page with html skeleton and tag script.
  • Initialize Variable color
  • var color = prompt("What color?" ) ;

    var color = prompt("What color?");

  • Check the value of a variable using a construct sweat, outputting for each value the corresponding translation:
  • switch (color) ( case "red" : alert("red"); break; case "green": alert("green"); break; // ...

    If the variable color has the value "red", then output to modal window translation - "red" and exit the structure (break;). If the variable color has the value “green”, then display the translation in the modal window - “green” and exit the structure (break;).

  • For flowers "blue" And "blue" do the grouping:
  • // ... case "blue": case "blue": alert("blue"); break; // ...

    If the variable color has the value "blue" or variable color has the value “blue”, then display the translation in the modal window - “blue” and exit the structure (break;).

  • Organize output for those colors that are not provided by the program:
  • // ... default : alert( "We have no information on this color") ) // end switch

    // ... default: alert("we have no information on this color") ) // end switch

  • Test the script in a browser.

Js task 3_6. Find and fix errors in the following code snippet:

14 15 16 17 var number = prompt( "Enter number 1 or 2:") ; switch (number) ( case "1" ( document.write ("One") ; ) ; break ; case "2" ( document.write ( "Two" ) ; ) ; break ; default ( document.write ( "You entered a value other than 1 and 2") ; } ; }

var number = prompt("Enter number 1 or 2:"); switch (number) ( case "1" ( document.write("One"); ); break; case "2" ( document.write("Two"); ); break; default ( document.write("You entered value other than 1 and 2"); ); )


Js task 3_7. What will be displayed on the screen when running the following code?:

1 2 3 4 5 6 7 8 9 10 11 12 13 var value = "2" ; switch (value) ( ​​case "1" : case "2" : case "3" : document.write ("Hello" ) ; break ; case "4" : case "5" : document.write ( "World" ) ; default : document.write ("Error" ) ; )

var value = "2"; switch (value) ( ​​case "1": case "2": case "3": document.write("Hello"); break; case "4": case "5": document.write("World"); default: document.write("Error"); )


Js task 3_8. Ask the user for a number - the number of crows on the branch. Depending on the entered number (no more than 10), display the message: - Sits on a branch 1 crow- Sits on a branch 4 crows- Sits on a branch 10 crows

  1. Depending on the number entered, the ending of the word changes "crow".
  2. To check, use the javascript Switch operator.
  3. Save this page in the results folder (it will be useful for further work).


Questions for self-control:

  1. In what case is it advisable as conditional operator use construction switch?
  2. What is the purpose of the default block in the statement? switch?
  3. Is it necessary to use the break statement in a construction? switch?
  4. How to group for multiple value options in a statement switch?

JavaScript cyclic operators - For

Syntax:

for(initial counter value; condition; counter increment) ( //..block of statements.. )

Important: A loop in javascript for is used when it is known in advance how many times cyclic actions should be repeated (how many iterations does the loop have)

  • An assignment expression is used as the initial value of the iteration counter: for example, i=0 - the loop counter starts from zero:
  • for(var i = 0; condition; counter increment) ( //..block of statements.. )

  • The increment of the counter specifies the step with which the counter should increase: for example, it indicates that each iteration of the loop will be accompanied by its increase by 1 :
  • for(var i = 0; condition; i++) ( //..block of statements.. )

  • The loop condition is the final value of the counter: for example, i10, stops the loop:
  • for(var i = 0; i<10; i++) { //..блок операторов.. }

Let's look at an example of using a for loop in javascript:

Example 5: Print a sequence of numbers 0 1 2 3 ... 9 , each digit is on a new line. 0 1 2 ... 8 9


✍ Solution:
  • To display a sequence of numbers, we will use a for loop counter, which should change its value from 0 before 9 according to the sequence.
  • So for initial value of the loop counter set the value to 0 ; as cycle conditions set the final value - ii=9; the counter step should be equal to 1 (i++), since the difference between the members of the sequence is one:
  • for (var i=0; i<10; i++) { document.write(i+"
    "); }

    In the example, the values ​​of the loop counter are displayed on the screen, since the increment of the i++ counter, accordingly, will appear on the screen 0 1 2 3 ... 9 , with each digit starting on a new line (tag
    ).

  • Test the script in a browser.

Js task 3_9. 1 before 15 .

  1. Use a loop counter as a sequence of numbers for.
  2. For an adder variable, use the variable identifier sum.

Code snippet:

For (var i=...;...;...)( sum = sum + ...; ) ...

Loop exit statements break And continue in JavaScript. Operator Exit

The break operator interrupts the execution of the entire loop body, i.e. exits a loop in javascript.

While the continue statement interrupts the execution of the current iteration of the loop, but continues the execution of the loop from the next iteration.

Let's look at the operation of the break and continue operators using an example:

Example: Disassemble the algorithm of the code fragment. What will be output?

Code snippet:

1 2 3 4 5 6 for (var i= 0 ; i< 10 ; i++ ) { if (i== 4 ) continue ; document.write (i+ "
" ) ; if (i== 8 ) break ; )

for (var i=0;i<10;i++) { if (i==4) continue; document.write(i+"
"); if (i==8) break; )


✍ Solution:
  • The third line of the example contains a condition due to which the number 4 will not be displayed: operator continue will move on to the next iteration of the loop without completing the current one.
  • Line No. 5 exits the loop, but at the same time the number 8 will be displayed on the screen, since the output statement comes before the condition (in the 4th line). Having met break, the interpreter will terminate the loop.
  • That. the screen will show: 0 1 2 3 5 6 7 8 - each digit is on a new line.

Task Js 3_10. Print the sum of all integers from 1 before 15 , excluding numbers from the total amount 5 And 7 .

Exit statement

The javasctipt language provides an operator for exiting program code - the exit operator.
The most common use of the operator is to eliminate user input errors.


Let's look at an example:

Example 6: Prompt the user to enter a number. If the entered number is not a number, then display a message "Need a number!" and stop the program.


✍ Solution:
  • Initialize Variable number value entered by the user in the modal window:
  • var number = prompt("Enter a number");

  • Using the parseInt function to convert a string to an integer, check whether the entered value is a number:
  • number=parseInt(number); // return NaN - not a number

    If the entered number is not a number, the function will return the value NaN (from English. not a number- not a number).

  • Check the value of a variable number using the isNaN function:
  • x = isNaN(number); // will return true if the value is not numeric

    The isNaN function returns the value true in case the variable is not a number

  • By the rule of "lies" organize checking the value of a variable x. If the value is not numeric, print the appropriate note and exit the program:
  • if (x)( alert("Number required!"); exit; // exit the program )

  • To continue the program (if the value entered was a number), display the following input prompt:
  • alert("Enter the second number");// if you enter a non-number, the operator will not be executed

  • Test the script in a browser.

Questions for self-control:

  1. List three loop parameters for and explain their purpose.
  2. What statements are used to exit a loop and to interrupt it? Give examples of their use.
  3. What is the purpose of the operator? exit?

Is it possible to have multiple counters in one FOR?

Interesting work with the for loop is possible when using simultaneously two counters in a loop.
Let's look at an example:

Example 7: Using the script, print the following variable-value pairs in three lines: i=0 j=2 i=1 j=3 i=2 j=4


✍ Solution:
  • In the for loop, organize two counters: counter i to print the sequence 0 1 2 , counter j for sequence output 2 3 4 :
  • 1 2 3 for (i= 0 , j= 2 ; i< 10 , j< 5 ; i++, j++ ) { }

    for(i=0, j=2; i<10, j<5; i++, j++) { }

    Each of the three parameters of the for loop now has two values, which are listed separated by commas(for example, the first parameter with two values: i=0, j=2). The parameters themselves are listed separated by semicolons(;).

  • To output from each line, use the tag
    :
  • 1 2 3 4 for (i= 0 , j= 2 ; i< 10 , j< 5 ; i++, j++ ) { document.write ("
    i=" , i, "j=" , j) ; )

    for(i=0, j=2; i<10, j<5; i++, j++) { document.write("
    i=", i, "j=",j); )

Generating a page on the fly: how is it?

Before performing the next task, let's look at an example dynamically building an html page using javascript.

Example 8:

  • You need to dynamically generate bulleted and numbered lists on a web page based on user input: prompt the user to enter list view(numbered (number 1) or marked (number 2)), and then number of list items.
  • Depending on the answer, display tags of either a bulleted or numbered list with the required number of items.
  • If a non-existent list type is entered, then display a message "Enter the correct type!" and exit the program ().

Let's remember the tags:
numbered list tags:

<ol > <li > <li > <li > </ol>

bulleted list tags:

var listType=prompt("Enter "1" - if a bulleted list, "2" - if a numbered list");

  • Check the entered value: for a numbered list (number 1) print the tag
      , for marked (number 2) - tag
        . If a different value is entered, print a note and end the program:

            ") else ( alert("Enter the correct type"); exit; )

          • Initialize Variable kolvo value entered by the user in the modal window:
          • var kolvo=prompt("Enter the number of points");

          • To convert a string value to a numeric value, use the parseInt function:
          • for (var i=1; i<=kolvo; i++) document.write("");

          • Since lists are closed with appropriate tags, depending on the type of list, print the closing tags:
          • if (listType== "1" ) document.write("" ) else if (listType== "2" ) document.write ("" ) ;

            if (listType=="1") document.write("

        ") else if (listType=="2") document.write("
      ");

    1. Test the script in a browser.
    2. Js assignment 3_11.
      Write a script that displays tags input(control elements) of different types, depending on the entered number:

      1 - text field,
      2 - button,
      3 - radio(switch).

      The number of tags displayed should also be requested.

      Let's remember the tags:

      For 1 - text field: For 2 - button: For 3 - radio:

      Example output:

      Assignment Js 3_12. Draw a 9x9 chessboard using javascript for loops. You should “draw” the board using html tags for the table:

      Let's remember the tags:

      <table border = "1" width = "30%" > <tr > <td >-</td> -</td> </tr> </table>

      --

      • To draw 9 lines, you need to organize an outer for loop with a counter i .
      • To draw 9 cells in each row, you need to organize an inner (nested) for loop with a counter j .
      • To render cell and row tags, you should use the document.write method.

      Result:

      Additionally:

      1. Display the multiplication table in the table cells using loop counters (i and j).
      2. Display the first row and first column with a red background (table cell attribute bgcolor):
        <td bgcolor = "red" >-</td>

        -

      Result:


      Questions for self-control:

      1. Explain what the concept of “dynamic page building” means?
      2. What language construct is most often used when building a page dynamically?

      javascript cyclic operators - while

      The syntax of the while statement is:

      while (condition) ( //..block of statements.. );

      Example: Display powers of two up to dialog box 1000 (2, 4, 8 ... 512). Use alert() method


      ✍ Solution:
      • Script listing:
      • 1 2 3 4 5 var a = 1 ; while (a< 1000 ) { a*= 2 ; alert(a) ; }

        var a = 1; while (a< 1000){ a*=2; alert(a); }

        a*=2 → the compound assignment operation was used: a product combined with an assignment, i.e. the same as a = a*2

      • Test the result in your browser.

      How do break and continue statements work in a while loop?

      Example:

      var a = 1 ; while (a< 1000 ) { a*= 2 ; if (a== 64 ) continue ; if (a== 256 ) break ; alert(a) ; }

      var a = 1; while (a< 1000){ a*=2; if (a==64) continue; if (a==256) break; alert(a); }

      Powers of two will be output up to 128 inclusive, and the value 64 will be missed. Those. in the dialog boxes we will see: 2 4 8 16 32 128

      Task Js 3_13. What values ​​will the following code snippet output?

      var counter = 5; while(counter< 10) { counter++; document.write("Counter " + counter); break; document.write("Эта строка не выполнится."); }


      Task Js 3_14. Write construction code X to the degree y using a while loop. Query the values ​​of variables and display the result using alert() .

      Complete the code:

      1 2 3 4 5 6 7 8 9 var x = ...; var y = ...; counter = 1 ; number= x; while (...) ( chislo= x* ...; counter= ...; ) alert(chislo) ;

      var x = ...; var y = ...; counter = 1; number=x; while (...)( chislo=x*...; counter=...; ) alert(chislo);

      A Correct the error in the program designed to find the factorial of a number:

      1 2 3 4 5 6 7 8 9 10 11 12 13 var counter = prompt("Enter a number" ) ; var factorial = 1 ; document.write( "Factorial of a number: "+ counter + "! = " ) ; do ( if (counter == 0 ) ( factorial = 1 ; break ; ) factorial = factorial / counter; counter = counter + 1 ; ) while (counter > 0 ) ; document.write(factorial);

      var counter = prompt("Enter a number"); var factorial = 1; document.write("Factorial of a number: " + counter + "! = "); do ( if (counter == 0) ( factorial = 1; break; ) factorial = factorial / counter; counter = counter + 1; ) while (counter > 0); document.write(factorial);


      Task Js 3_16. Modify the program for the user to enter a name:

      Prompt for a username until the user actually enters a name (i.e. the field is actually filled in and the cancel key is not pressed). When the name is entered, then display "Hello, name!". document.

      How to find errors in javascript?

      In some cases, the code on the page does not work for some unknown reason. Where to look for the error? In such cases, you can use the try..catch operator.

      The try..catch statement attempts to execute a piece of code, and if there is an error in the code, it is possible to display the error on the screen.
      The error is stored in the e.message object.

      Let's look at the operator's work using an example:

      Example: write an error statement in the program. Check for errors in the supposed erroneous code: if there is an error in the code, display a message "error handling: error name". After checking the erroneous statement, regardless of whether there is an error in the code, display the message "final actions"


      ✍ Solution:
      • As an error message, we will use the prompt() method, written with an error - prompt(). Enclose the error message in a try block:
      • alert("before"); try ( promt("enter a number"); // statement with error )

        Try from English - “try”, thus we put the try statement before a piece of code that may contain an error (in our case there really is an error).

      • The error message should be placed in a catch block:
      • 6 7 8 9 catch (e) ( alert( "error handling: "+ e.message); )

        catch(e) ( alert("error handling: "+e.message); )

        If there really is an error, then the catch operator stores this error in the e object. In the future, it can be displayed in a dialog box - e.message.

      • Place the final message, which must be output regardless of whether there is an error in the code, in a finally block:
      • finally ( alert("final actions"); ) alert("after");

        If there is still an error, then the interpreter, after printing it in our example, will proceed to execute the catch block, and then finally (from English “completion”, “finally”), which will always be executed, regardless of whether there was an error or not. Even if there is an error in the catch block.

      Important: The finally block in the construct is optional.


      Task Js 3_17. Follow the example above with the following modifications:

    3. Remove the finally block and monitor the execution of the code.
    4. Replace the erroneous operator with an error-free one and see what the result is.
    5. Summary:

      The lesson covered the following javascript language operators and constructs:

      Javascript conditional statements:

    6. if statement
    7. Conditional assignment (ternary operator)
    8. switch statement
    9. Loop operators:

    10. for loop
    11. while loop
    12. do...while loop
    13. For...in loop
    14. Final assignment Js 3_18.
      Create a game for two:

      1. The program asks the first player to enter a number from 1 before 100 (the second player does not see the entered number). The second player is then asked to guess the entered number. A message is displayed in response "few" or "a lot of" depending on the answer entered. If the player guesses correctly, a congratulation is displayed. If he doesn’t guess, the game continues (until the number is actually guessed).
      2. Count the number of attempts and produce a result when the number is solved.


      Questions for self-control:

      1. When is it appropriate to use a For In loop? Give an example of its use.
      2. What is the purpose of the try..catch statement?
      3. Explain the purpose of each try..catch statement block.


  • tell friends