Java script operators. Expressions and operators. Comments in JavaScript
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 JavaScriptOperands are the data processed by the JavaScript script. The operands can be: simple types data, and complex, as well as other expressions.
Operators are language symbols that perform various operations on 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 an expression is a 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 operatorsArithmetic operators are designed to perform mathematical operations; they operate on numeric operands (or variables that store numeric values), returning as a result numeric value.
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).
+ 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 |
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 operatorsThe increment and decrement operations 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 operatorsComparison operators are used to compare 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.
== 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 |
Logical operators allow you to combine conditions that return Boolean 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 operatorsBitwise operators operate on their operands as a 32-bit sequence of ones and zeroes and return a numeric value indicating the result of the operation, written in decimal system Reckoning. Integers are considered as operands. fractional part the operand is discarded. Bitwise operations can be used, for example, when encrypting data, working with flags, and delineating access rights.
& 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 | Performs a bitwise negation operation 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 numbers 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 left unchanged 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 |
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 ? x * 2: x / 2; // returns x * 2 if x > 10, otherwise x / 2 9. Comments in JavaScriptSingle-line comment: you must precede the comment text with the symbols // .
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:
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.
Block starting with function word default can be omitted. 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 display... break default: // else alert("Many"); // otherwise 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
- Check the value of a variable using a construct sweat, outputting for each value the corresponding translation:
- For flowers "blue" And "blue" perform grouping:
- Organize output for those colors that are not provided by the program:
- Test the script in a browser.
var color = prompt("What color?" ) ; |
var color = prompt("What color?");
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;).
// ... 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;).
// ... default : alert("we have no information for this color" ) ) // end switch |
// ... default: alert("we have no information on this color") ) // end switch
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 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: - 1 crow is sitting on a branch - 4 crows are sitting on a branch - 10 crows are sitting on a branch
Questions for self-control:
Syntax:
for(initial counter value; condition; counter increment) ( //..block of statements.. )
Important: The 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:
- 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:
- The loop condition is the final value of the counter: for example, i10, stops the loop:
for(var i = 0; condition; counter increment) ( //..block of statements.. )
for(var i = 0; condition; i++) ( //..block of statements.. )
for(var i = 0; i