Operators
3. The operators:
A. Arithmetic operators
In the first examples of this manual, only very simple statements have been used as assigning a value to a variable, using the assignment operator, =, or perform arithmetic operations, but evidently JavaScript can perform more operations.
In this section and the following are presented, operators available to this language classified into several groups, according to the context in which they are used. We begin with the best known, arithmetic operators.
Sum +
It is an operator used to add two numerical values or to concatenate chains with each other or numbers and chains.
let var1 = 10, var2 = 'Good', var3 = ' morning', var4 = 31;
logger.warn(var1+var4) /* Result 41 */
logger.warn(var2+var3) /* Result: Good morning*/
logger.warn(var1+var3) /* Result: 10 morning*/
subtraction -
Operator used to subtract numerical values. You can act on a single numerical operand changing it sign.
let num1 = 10, num2 = 8, res = 0;
res = num1 - num2; /*res contains 2 */
res = -res /* Now res contains -2*/
Product (*) and quotient (/)
let op1 = 50, op2= 4, div, mul;
div = op1/op2 /*div contains 12.5 */
mul = op1 * op2 /*mul will contains 200 */
Rest %
Also called operator module calculates the rest of a division.
let op1 = 50, op2 = 4, resto;
rest = op1 % op2; /*rest contains 2 */
Increase ( ++) y decrease (--)
These operators are used to increase or decrease in the value of a variable. If the operator pretends to the variable, the increase or decrement operation is a priority on any other.
let op1 = 5, op2 = 5, res;
res = ++op1; /*res acquire the value 6 and then op1 on 6*/
res = op2++; /*res acquire the value 5 and then op2 on 6*/
Compound operators
Operators +, -, *, \/ can be associated with the assignment operator (=) to change the value of a numerical variable by increasing it, decrementing it, multiplying it or dividing it for a value. The operator += can be used equally with string variables.
let num = 20, str = 'good';
num += 5; /*num adquire the value 25 (20 + 5) */
str += 's' ; /*str adquiere el valor 'goods' */
num *= 10; /*num adquiere el valor 250 (25*10) */
B. Binary operators
Complementation ~
Complements a binary chain by converting the 1 in 0 and 0 in 1. For example, the number 38 written in binary system is 00100110 if we apply this operator becomes 11011001, that is the -39 (JavaScript uses coding in complement to 2 for The negative numbers).
Left displacement <<
Scrolls the bits to the left the places that are indicated by filling with zeros on the right and discarding the bits of greater weight, this is equivalent to multiplying by powers of 2. for example if at 00011010 (26) we move 2 to the left we will have 01101000 (104).
let num = 26, res;
res = num << 2; /* res value is 104 */
Right displacement >>
Scrolls the bits to the right The places indicated by filling with zeros on the left and discarding the lower weight bits, this is equivalent to a whole division by powers of 2. For example if at 00011010 (26) we move 2 to the Right we will have 00000110 (6).
let num = 26, res;
res = num >> 2; /* res value is 6 */
AND binary logic &
Perform a logical bit to Bit between two values. The logical and logical results 1 only if both bits are 1. for example 01101101 (109) and 00100110 (38) Result: 00100100 (36)
```js let op1 = 109, op2 = 38, res; res = op1 & op2; /res value is 36 /
#### OR binary logic |
Perform a logical bit to Bit between two values. The logical OR results in 0 only if both bits are 0. for example
00111010 (58) OR 01010010 (82) Outcome: 01111010 (122)
In the example we can see the syntax of the operator
```js
let op1 = 58, op2 = 82, res;
res = op1 | op2; /*res value is 122 */
XOR binary logic ^
Perform a logical bit to Bit between two values. The logical XOR gives as a result 1 if one of the bits is 1. For example 00111010 (58) OR 01010010 (82) Outcome: 00101000 (40) In the example we can see the syntax of the operator
let op1 = 109, op2 = 38, res;
res = op1 ^ op2; /*res value is 40*/
C. Logical operators
Logical operators are used to make comparisons between values, numerical or not, resulting in a value boolean (true, false). The logical operation Denial Inverts the operand, if it is true does it false and vice versa. If numbers are compared with chains, JavaScript tries to internally convert the data. In relational operators (>, <, >=, <=) try converting data into number type. For equal operators (== !=) try converting data types to string, number and Booleano.. Identity operators (===, !==) do not perform type conversion.
Greater than >
Compare two values and returns true if the first is greater than the second. Compare both numbers and strings.
let today = 4, yesterday = 10, comp;
comp = today > yesterday /* comp value is false*/
Smaller than <
Compare two values and returns true if the first is greater than the second. Compare both numbers and strings.
let today = 4, yesterday = 10, comp;
comp = today < yesterday /* comp value is false*/
Greater or equal >=
Compare two values and returns true if the first is greater or is the same as the second. Compare both numbers and strings.
let today = 4, yesterday = 4, comp;
comp = today >= yesterday /* comp value is true*/
Smaller or equal <=
Compare two values and returns true if the first is less or is the same as the second. Compare both numbers and strings.
let today = 4, yesterday = 4, comp;
comp = today <= yesterday /* comp value is true*/
Equal ==
Compare two values and returns true if both are equal. Compare both numbers and strings.
let today = 4, yesterday = 4, comp;
comp = today == yesterday /* comp value is true*/
Identical ===
Similar to == but also compares the type of opeand data. Compare two values and returns true if the first is equal to the second and the data type of both is the same. Compare both numbers and strings.
let today = 4, yesterday = '4', comp;
comp = today == yesterday; /* comp value is true*/
comp = today === yesterday; /* comp value is false*/
Not equal != No identical !==
They invert the meaning of equal comparisons == and identical === respectively.
AND logical &&
This operator is used to concatenate comparisons, that is, to check several conditions. The result will only be true if all comparisons are.
let op1 = 2, op2 = 50, op3 = 25, comp;
comp = (op1 > op2) && (op1 < op3); /*comp value is false */
comp is false because op1 is not greater than op2 even if it is less than op3
OR logical ||
As the previous one, it serves to make composite comparisons and will only return false when all comparisons are. That is, it is enough that a comparison is true to return the true value.
let op1 = 2, op2 = 50, op3 = 25, comp;
comp = (op1 > op2) || (op1 < op3); /*comp value is true */
comp is true why op1 is less than op3, although op1 is not greater than op2
D. Various operators
delete
It is used to erase properties from an object or elements of an array. Returns true if the operation was successfully performed.
let list = new Array(1, 4, 7, 9, 10);
delete(list,0);
The list element [1] now contains Undefined.
new
It is used to create instances of an object
let today = new Date('10/30/2000')
typeof
Returns the type of data to which a variable or expression belongs. Returned types are number, string, boolean, object, function and undefined.
let today = 1.2345;
type = typeof(today);
The variable type will contain number.
E. Global functions
Yes, as JavaScript provides predefined objects, it also has a series of predefined functions. It is about the functions: eval, isNan, Number, String, parseInt, parseFloat, escape, unescape.
eval
It is used to evaluate a chain with JavaScript code without referring to a specific object. The syntax of eval is:
eval(expr)
where expr is the chain to be evaluated.
isNaN(arg)
Determines if the argument is a value NaN (not a number)
parseInt(str, [base])
Convert a string of characters into a numerical value. The function leads the string to be converted as an argument and optionally can take a second argument to indicate the numbering base in which the chain is written.
If it is omitted, it is assumed that the string represents a number based on 10. The string may contain valid characteristics for the numbering system indicated: digits (0..9 for base 10, 0 1 for binary numbers, 0..7 for octal system, 0..9, a..f for hexadecimal system) and sign (+, -).
If you find any invalid character, it only interprets from the beginning of the chain to the invalid nature. If it begins by an illegal character returns NaN. Example:
let minum1 = '14';
logger.warn(parseInt(minum1));
Write it 14. In the following example, it transforms a binary number to decimal:
let minum1 = '11001';
logger.warn(parseInt(minum1, 2));
Now he will write 25, the decimal equivalent to the binary 11001.
parseFloat(str)
They convert a string that is passed as an argument at a floating-type numerical value. The valid characters of the string are the same as in parseint plus the decimal point and the exponent (E). It does not support a second argument. Otherwise it works exactly as parseint.
let minum1 = '14.5E2';
logger.warn(parseInt(minum1));
Write the number 1450, 14.5 per 10 elevated to 2.
Number(objArg) and String(objArg)
They allow us to convert the past object as an argument to a number or a chain. For instance:
let today = new Date();
hoy.getDate();
logger.warn(string(today));
You will write the string "Sun Sep 3 20:40:05 UTC + 0200 2000" If the date of the day is Sunday, September 3 and the time is 20:40:05.
escape(cadarg)
Codes the argument chain by replacing all the non-ASCII characters for its code in the% XX format. For instance:
let cadena = 'Buenos días';
logger.warn(escape(cadena));
Produce the phrase "Buenos d%EDas", Well, the í. (i accentuous) is the Hexadecimal ED code of that character.
unescape(cadarg)
It is inverse to the previous one, so that if the chain contains codes of type% XX are converted to the corresponding extended ASCII character.
let cadena = 'Buenos d%EDas';
logger.warn(escape(cadena));
Now it will be written 'Buenos días', %ED has been replaced by its equivalentí (i accentuous).
F. Regular expressions
The regular expressions constitute a rather powerful mechanism for manipulating text strings. The process for which these expressions are used, present in the world UNIX and the Perl language, is to search and/or replace a text subcade within another string.
In principle this can be done using the methods of the object string, but the problem arises when we do not have a fixed and concrete subcade but we want to look for a text that responds to a certain scheme, such as: looking for those words that begin with http: and end with one \, or look for words that contain a series of consecutive numbers, etc.; It is in these cases when regular expressions show all its power.
The substring that we seek in the text is what is called a pattern and is built by enclosing between two inclined bars ( / ) a series of normal characters and special symbols called wildcards or metacharacters, (Something similar to the order dir *.bat used at the DOS when we wanted to list the files with bat extension).
This pattern is a description of the text you are looking for and JavaScript will find the subcakes that match that pattern or definition. Regular expressions are used with the object Regular Expresion And also within the methods String.match , String.replace , String.search and String.split.
In the following table, the wildcard characters used are displayed to create patterns and their meaning, along with a small example of their use.
| Meaning | Example | Result | |
|---|---|---|---|
| \ | Mark of special character | /\$ftp/ | Look for the word $ftp |
| ^ | Beginning of a line | /^-/ | Lines beginning with - |
| $ | End of a line | /s$/ | Lines that end by s |
| . | Any character (less line jump) | \b.\b/ | Words of a single letter |
| | | Indicates options | /(L|l|f|)ocal/ | Seeks Local, local, focal |
| ( ) | Group characters | /(vocal)/ | Seeks vocal |
| [ ] | Optional character set | /escrib[aoe]/ | are worth: escriba, escribo, escribe |
The table that follows describes the modifiers that can be used with the characters forming the pattern. Each modifier acts on the character or the parentheses immediately above.
| Description | Example | Result | |
|---|---|---|---|
| * | Repeat 0 or more times | /l*234/ | Are worth: 234, 1234, 11234... |
| + | Repeat 1 or more times | /a+mar/ | Are worth: amar, aamar, aaamar... |
| ? | 1 or 0 times | /a?mar/ | Are worth: amar, mar. |
| {n} | Exactly n times | /p{2}sado/ | Are worth: ppsado |
| {n,} | At least n times | /(m){2,}ala/ | Are worth: mmala, mmmala.... |
| {m,n} | between m and n times | /tal{1,3}a/ | Are worth: tala, talla, tallla |
The following are special characters or metacharacters to indicate non-printable text characters, such as the line of line or a tab, or predefined character groups (alphabetic, numerical, etc ...)
| Description | Example | Result | |
|---|---|---|---|
| \b | Principle or end of the word | /\bver\b/ | Find ver in "ver de" , but not in "verde" |
| \B | Border between non-words | /\Bver\B/ | Match ver with "Valverde" But not with "verde" |
| \d | A digit | /[A-Z]\d/ | Not failla in "A4" |
| \D | Alphabetical (no digit) | /[A-Z]\D/ | He would fail in "A4" |
| \O | Null character | ||
| \t | Character ASCII 9 (tabulator) | ||
| \f | Page jump | ||
| \n | Line jump | ||
| \w | Any alphanumeric, [a-zA-Z0-9_ ] | /\w+/ | Find frase in " frase .", but not the . (point). |
| \W | Opposite to \w ([^a-zA-Z0-9_ ]) | /\W/ | I would find only the point (.) |
| \s | Space type character (like Tab) | /\sYes\s/ | Find Yes in "Say Yes ", but not in "Say Yesterday" |
| \S | opposite to \s^ | ||
| \cX | Character of control X | \c9 | The tab |
| \oNN | Octal character NN | ||
| \xhh | The hexadecimal hh | /\x41/ | Find the A (ASCII Hex41) en "letter A" |