Division modulo javascript. Arithmetic Operations in JavaScript

Are you familiar with arithmetic? Can you add and subtract numbers? JavaScript can also add and subtract. JavaScript has the following operators: addition +, subtraction -, division /, multiplication *, division with remainder %.

Var one = 121;
var two = 13;
alert(one + two);
alert(one - two);
alert(one * two);
alert(one / two);
alert(one % two);

Let's complicate example 1

Var answer = ((121 - 12) * 103) + 200;
alert(answer);

Let's complicate example 2

VarPI = 3.14;

alert(answer);

And let’s complicate the third example

VarPI = 3.14;
var answer = ((121 - 12) * 103) + PI;
var answerEnd = (2 * answer * PI) + (-100);
alert(answerEnd);

And even this can be done

Var answer = 101 + (-(-100));
alert(answer);

But this is nonsense compared to what JavaScript can do. For this purpose, there is a standard Math object with many properties (properties are operations, in this context).

Math.pow(2, 53) /* -> 2 to the power of 53 */
Math.round(0.6) /* -> 1.0 - round to the nearest integer */
Math.ceil(0.6) /* -> 1.0 - round up */
Math.floor(0.6) /* -> 0.0 - round down */
Math.abs(-5) /* -> 5 - modulus, absolute value */
Math.max(x, y, z) /* -> Returns the largest argument */
Math.min(x, y, z) /* -> Returns the smallest argument */
Math.random(); /* -> Where the output number is greater than 0 but less than 1 */
Math.PI /* -> Pi */
Math.E /* -> Base of natural logarithm */
Math.sqrt(3) /* -> Square root of 3 */
Math.pow(3, 1/3) /* -> Cube root of 3 */
Math.sin(0) /* -> Trigonometry: there are also Math.cos, Math.atan and others */
Math.log(10) /* -> Natural logarithm 10 */
Math.log(100) / Math.LN10 /* -> Logarithm of 100 base 10 */
Math.log(512) / Math.LN2 /* -> Logarithm of 512 base 2 */
Math.exp(3) /* -> Math.E cubed */

How to use the Math object?

/* First example */
var twoInPow = Math.pow(2, 53);
alert(twoInPow);
/* Second example */
var valueRaund = 0.1312;
var answerRaunt = Math.round(valueRaund);
alert(answerRaunt);
/* Third example */
var valueRaund = 0.1312;
alert(Math.round(valueRaund));
/* Fourth example: finding the largest of three numbers */
var a = 12, b = 11, c = 10;
alert(Math.max(a, b, c));

In case of out of range, loss of significant digits, or division by zero, JavaScript does not throw an error. If the result is too large and out of range, then a special value “infinity” will be returned, it looks like this “Infinity”.

Loss of significant digits: The result of an arithmetic operation is very close to zero. If there was a loss, then 0 (zero) will be returned.

The global variable NaN means "not a number". There is one peculiarity of this variable: the equality test operation (==) always returns a negative result, even if it is compared with itself.

/* You can’t write like that */
if (x == NaN) ( ... )

To determine whether the value of a variable x is a NaN value, you need to use the construction below. This check will only evaluate to true when x is equal to NaN


Arithmetic operators and type casting

JavaScript supports the following arithmetic operators:

An interesting feature of JavaScript is the ability to perform arithmetic operations on variables various types. In this case, the interpreter performs the type cast itself and performs the specified operation. The following rules are used in the type maintenance process:

1. If one of the operands is a string, then all other operands are converted to string form.

Var1 = "Uncle" var2 = "Vanya" result = var1 + " " + var2 // result = "Uncle Vanya" mixed = var2 + 100 // mixed = "Vanya100"

2. All logical operands are converted to numeric form, except when all the operands in the expression are logical. In this case, true is reduced to "1", and false - to "0". When combining logical operands with strings, all operands are converted to text form.

Var1 = true var2 = true result = var1 + var2 // result = 2 mixed = var2 + 100 // mixed = 101 var3 = "string:" str = var3 + var1 // str = "string:true"

3. If type casting fails, the result of the expression will be “NaN” (for example, when trying to split a string into something).

Var1 = "Uncle" var2 = "Vanya" result = var1 / var2 // result = "NaN" mixed = var2 * true // mixed = "NaN"

However, at the initial stage it is better to refrain from casting types and tricks with transforming results. This will save you from a significant number of errors.

Math object

The Math object contains basic mathematical constants and standard mathematical functions. The most commonly used ones are shown in the table:

Properties
LN10 The value of the natural logarithm of the number 10
LN2 The value of the natural logarithm of the number 2
P.I. Pi value
Methods
abs(number) Returns the absolute value of a number (i.e. the number without taking into account its sign)
ceil(number) Rounds a number to the nearest higher integer (round up)
exp(number) Returns the number "e" to the power of "number"
floor(number) Rounds a number to the nearest lower integer (round down)
max(number1, number2) Returns the larger of two numbers
min(number1, number2) Returns the smaller of two numbers
pow(number1, number2) Returns "number1" raised to the power "number2"
random() Returns a random number in the range from 0 to 1
round(number) Rounds a number according to standard rounding rules
sqrt(number) Returns the square root of a number.

Of all the listed functions, it makes sense to further explain only ceil(), floor() and round(). Let's look at their differences using an example:

Num = 1.222 // nearest integer "down" is 1 // nearest integer "up" is 2 // arithmetically rounded to 1 alert(Math.ceil(num)) alert(Math.floor(num)) alert(Math.round (num)) // we get three messages: 2, 1, 1 num = 1.777 // the nearest integer "down" is 1 // the nearest integer "up" is 2 // arithmetically rounded to 2 alert(Math.ceil(num) ) alert(Math.floor(num)) alert(Math.round(num)) // we get three messages: 2, 1, 2

Math set JavaScript functions allows you to solve a fairly wide range of problems, but you shouldn’t abuse it. Do not forget that the code is executed by an interpreter, but there is no question of low-level optimization of calculations, therefore high performance will be very difficult to achieve.

The operators: - (subtraction), + (addition), * (multiplication) and / (division) work exactly the same as arithmetic operations in mathematics. Operator % ( division with remainder) returns the remainder when the first operand is divided by the second. The result of division with a remainder will have the same sign as the first operand:

Alert(10 + 2); // 12 alert(10 - 2); // 8 alert(10 * 2); // 20 alert(10 / 2); // 5 alert(5 % 2); // 1 alert(-5 % 2); // -1

Operator ** ( exponentiation) has two operands. The first operand is the base of the power, the second operand is the exponent, so the operator returns the base raised to the specified power:

2 ** 4; // 16

All mathematical operators convert their operands using the same rules as the Number() function.

Unary + (plus) and - (minus)

The + operator (unary plus) converts the value of its operand to a number and returns the converted value. When used with a numeric operand, it does nothing:

Var x = +"5";

The - (unary minus) operator converts the value of its operand to a number if necessary, and then makes the number negative:

Var x = -5 + 3;

Unary plus and minus convert their operands using the same rules as the Number() function.

Increment and decrement

The ++ (increment) operator increases the value of its operand by one. If the operand's value is not a number, the operator automatically converts it to a number, increments it by one, and returns the result, which is assigned back to the operand.

Increment has two forms - postfix (the operator is placed after the operand) and prefix (the operator is placed before the operand). If it is used in postfix form, then it is returned first original value operand, and only then the value of the operand is incremented by one.

Very often, calculations in JavaScript do not give exactly the results we want. Of course, we can do whatever we want with numbers - round up or down, set ranges, cut off unnecessary numbers to a certain number of decimal places, it all depends on what you want to do with this number in the future.

Why is rounding necessary?

One of the interesting aspects of JavaScript is that it doesn't actually store integers, we work straight away with floating point numbers. This, combined with the fact that many fractional values ​​cannot be expressed in a finite number of decimal places, in JavaScript we can get results like this:

0.1 * 0.2; > 0.020000000000000004 0.3 - 0.1 > 0.19999999999999998
For practical purposes, this inaccuracy does not matter, in our case we are talking about an error in quintillion parts, however, this may disappoint some. We can also get somewhat strange results when working with numbers that represent currencies, percentages, or file sizes. In order to correct these inaccuracies, we just need to be able to round the results, and it is enough to set the decimal precision.

Rounding numbers has practical applications, we can manipulate a number within a certain range, for example we want to round a value to the nearest whole number rather than working only with the decimal part.

Rounding decimal numbers

In order to cut off decimal number, use toFixed or the toPrecision method. Both of them take a single argument that specifies, respectively, how many significant figures (that is, the total number of digits used in the number) or decimal places (the number after the decimal point) the result should include:
  1. If an argument is not defined for toFixed() then it will default to zero, which means 0 decimal places the argument has maximum value, equal to 20.
  2. If no argument is given to toPrecision, the number is left untouched
let randNum = 6.25; randNum.toFixed(); > "6" Math.PI.toPrecision(1); > "3" randNum = 87.335; randNum.toFixed(2); > "87.33" randNum = 87.337; randNum.toPrecision(3); > "87.3"
Both the toFixed() and toPrecision() methods return a string representation of the result, not a number. This means that when summing a rounded value with randNum, it will produce a concatenation of strings rather than a sum of numbers:

Let randNum = 6.25; let rounded = randNum.toFixed(); // "6" console.log(randNum + rounded); > "6.256"
If you want the result to be a numeric data type, then you will need to use parseFloat:

Let randNum = 6.25; let rounded = parseFloat(randNum.toFixed(1)); console.log(rounded); > 6.3
Please note that values ​​of 5 are rounded except in rare cases.

The toFixed() and toPrecision() methods are useful because they can not only cut off the fractional part, but also add decimal places, which is convenient when working with currency:

Let wholeNum = 1 let dollarsCents = wholeNum.toFixed(2); console.log(dollarsCents); > "1.00"
Note that toPrecision will produce the result in scientific notation if the number of integers is greater than the precision itself:

Let num = 123.435 num.toPrecision(2); > "1.2e+2"

How to Avoid Rounding Errors with Decimals

In some cases, toFixed and toPrecision rounds the value 5 down and up:

Let numTest = 1.005; numTest.toFixed(2); > "1.00"
The result of the calculation above should have been 1.01, not 1. If you want to avoid a similar error, we can use the solution proposed by Jack L Moore, which uses exponential numbers for the calculation:

Function round(value, decimals) ( return Number(Math.round(value+"e"+decimals)+"e-"+decimals); )
Now:

Round(1.005,2); > 1.01
If you want a more robust solution than the one shown above, you can go to MDN.

Machine epsilon rounding

An alternative method for rounding decimal numbers was introduced in ES6. Machine epsilon rounding provides a reasonable margin of error when comparing two floating point numbers. Without rounding, comparisons may produce results similar to the following:

0.1 + 0.2 === 0.3 > false
We use Math.EPSILON in our function to get a valid comparison:

Function epsEqu(x, y) ( return Math.abs(x - y)< Number.EPSILON * Math.max(Math.abs(x), Math.abs(y)); }
The function takes two arguments: the first is the current calculation, the second is the expected result. It returns a comparison of the two:

EpsEqu(0.1 + 0.2, 0.3) > true
All modern browsers already support ES6 math functions, but if you want support in browsers like IE 11, use polyfills.

Trimming the fractional part

All methods presented above can round to decimal numbers. In order to simply cut a number to two decimal places, you must first multiply it by 100, and then divide the resulting result by 100:

Function truncated(num) ( return Math.trunc(num * 100) / 100; ) truncated(3.1416) > 3.14
If you want to adapt the method to any number of decimal places, you can use bitwise double negation:

Function truncated(num, decimalPlaces) ( let numPowerConverter = Math.pow(10, decimalPlaces); return ~~(num * numPowerConverter)/numPowerConverter; )
Now:

Let randInt = 35.874993; truncated(randInt,3); > 35.874

Round to the nearest number

To round a decimal number to the nearest number up or down, whichever we're closest to, use Math.round():

Math.round(4.3) > 4 Math.round(4.5) > 5
Please note that “half the value”, 0.5 is rounded up according to the rules of mathematics.

Round down to the nearest whole number

If you want to always round down, use Math.floor:

Math.floor(42.23); > 42 Math.floor(36.93); > 36
Please note that rounding down works for all numbers, including negative numbers. Imagine a skyscraper with an infinite number of floors, including floors on the bottom level (representing negative numbers). If you are in an elevator on the lowest level between 2 and 3 (which represents a value of -2.5), Math.floor will take you to -3:

Math.floor(-2.5); > -3
But if you want to avoid this situation, use Math.trunc , which is supported in all modern browsers(except IE/Edge):

Math.trunc(-41.43); > -41
On MDN you will find a polyfill that will provide support for Math.trunc in browsers and IE/Edge.

Round up to the nearest whole number

On the other hand, if you always need to round up, use Math.ceil. Again, remember the infinite elevator: Math.ceil will always go "up", regardless of whether the number is negative or not:

Math.ceil(42.23); > 43 Math.ceil(36.93); > 37 Math.ceil(-36.93); > -36

Rounding up/down to the required number

If we want to round to the nearest multiple of 5, the easiest way is to create a function that divides the number by 5, rounds it, and then multiplies it by the same amount:

Function roundTo5(num) ( return Math.round(num/5)*5; )
Now:

RoundTo5(11); > 10
If you want to round to multiples of your value, we use a more general function, passing in the initial value and the multiple:

Function roundToMultiple(num, multiple) ( return Math.round(num/multiple)*multiple; )
Now:

Let initialNumber = 11; let multiple = 10; roundToMultiple(initialNumber, multiple); > 10;

Fixing a number in a range

There are many cases where we want to get a value of x that lies within a range. For example, we might need a value between 1 and 100, but we ended up with a value of 123. To fix this, we can use min (returns the smallest of a set of numbers) and max (returns the largest of any set of numbers). In our example, the range is from 1 to 100:

Let lowBound = 1; let highBound = 100; let numInput = 123; let clamped = Math.max(lowBound, Math.min(numInput, highBound)); console.log(clamped); > 100;
Again, we can reuse the operation and wrap the whole thing in a function, using the solution proposed by Daniel X. Moore:

Number.prototype.clamp = function(min, max) ( return Math.min(Math.max(this, min), max); );
Now:

NumInput.clamp(lowBound, highBound); > 100;

Gaussian rounding

Gaussian rounding, also known as banker's rounding, involves rounding to the nearest even number. This rounding method works without statistical error. The best decision was suggested by Tim Down:

Function gaussRound(num, decimalPlaces) ( let d = decimalPlaces || 0, m = Math.pow(10, d), n = +(d ? num * m: num).toFixed(8), i = Math.floor (n), f = n - i, e = 1e-8, r = (f > 0.5 - e && f< 0.5 + e) ? ((i % 2 == 0) ? i: i + 1) : Math.round(n); return d ? r / m: r; }
Now:

GaussRound(2.5) > 2 gaussRound(3.5) > 4 gaussRound(2.57,1) > 2.6
Decimal in CSS:

Since JavaScript is often used to create positional mappings for HTML elements, you might be wondering what would happen if we generated decimal values ​​for our elements:

#box ( width: 63.667731993px; )
The good news is that modern browsers will respect decimal values ​​in the block model, including percentage or pixel units.

Sorting

Very often we have to sort some elements, for example, we have an array of game records, and they must be organized in descending order of player rank. Unfortunately, the standard sort() method has some surprising limitations: it works well with common English words, but immediately breaks down when it encounters numbers, unique characters, or uppercase words.

Sorting alphabetically

It would seem that sorting an array alphabetically should be a simple task:

Let fruit = ["butternut squash", "apricot", "cantaloupe"]; fruit.sort(); > "apricot", "butternut squash", "cantaloupe"]
However, we run into a problem as soon as one of the elements is uppercase:

Let fruit = ["butternut squash", "apricot", "Cantalope"]; fruit.sort(); > "Cantaloupe", "apricot", "butternut squash"]
This is because, by default, the sorter compares the first character represented in Unicode. Unicode is a unique code for any character, regardless of platform, regardless of program, regardless of language. For example, if you look at the code table, the character "a" has the value U+0061 (in hexadecimal 0x61), while the character "C" has the code U+0043 (0x43), which comes earlier in the Unicode table than the character "a".

To sort an array that may contain mixed case first letters, we need to either convert all elements temporarily to lower case, or define our sort order using the localeCompare() method with some arguments. As a rule, for such a case, it is better to immediately create a function for repeated use:

Function alphaSort(arr) ( arr.sort(function (a, b) ( return a.localeCompare(b, "en", ("sensitivity": "base")); )); ) let fruit = ["butternut squash ", "apricot", "Cantaloupe"]; alphaSort(fruit) >
If you want the array sorted in reverse alphabetical order, simply swap the positions of a and b in the function:

Function alphaSort(arr) ( arr.sort(function (a, b) ( return b.localeCompare(a, "en", ("sensitivity": "base")); )); ) let fruit = ["butternut squash ", "apricot", "Cantaloupe"]; alphaSort(fruit) > ["Cantaloupe", "butternut squash", "apricot"]
Here it is worth noting that localeCompare is used with arguments, we also need to remember that it is supported by IE11+, for older versions of IE, we can use it without arguments, and in lowercase:

Function caseSort(arr) ( arr.sort(function (a, b) ( return a.toLowerCase().localeCompare(b.toLowerCase()); )); ) let fruit = ["butternut squash", "apricot", "Cantaloupe"]; caseSort(fruit) > ["apricot", "butternut squash", "Cantaloupe"]

Numeric sort

All this does not apply to the example we talked about above about the array of game records. With some numeric arrays, sorting works just fine, but at some point the result can be unpredictable:

Let highScores = ; highScores.sort(); >
The thing is that the sort() method performs a lexicographic comparison: which means that the numbers will be converted into a string and the comparisons will again be made by matching the first character of that string in the order of the characters in the Unicode table. Therefore, we again need to define our sort order:

Let highScores = ; highScores.sort(function(a,b) ( return a - b; )); >
Again, to sort numbers in reverse order, swap the positions of a and b in the function.

Sorting a JSON-like structure

And finally, if we have a JSON-like data structure represented as an array of game records:

Let scores = [ ( "name": "Daniel", "score": 21768 ), ( "name": "Michael", "score": 33579 ), ( "name": "Alison", "score": 38395 ) ];
In ES6+, you can use arrow functions:

Scores.sort((a, b) => b.score - a.score));
For older browsers that do not have this support:

Scores.sort(function(a, b) ( return a.score - b.score ));
As you can see, sorting in JavaScript is a rather obscure thing, I hope that these examples will make life easier somehow.

Working with power functions

Exponentiation is an operation originally defined as the result of repeatedly multiplying a natural number by itself; the square root of a is the number that gives a when squared. We could use these functions constantly in Everyday life in math lessons, including calculating areas, volumes, or even physical modeling.

In JavaScript, the power function is represented as Math.pow(), and in the new ES7 standard, a new exponentiation operator was introduced - " * * ".

Exponentiation

To raise a number to the nth power, use the Math.pow() function, where the first argument is the number that will be raised to the power, the second argument is the exponent:

Math.pow(3,2) > 9
This form of notation means 3 squared, or 3 × 3, which leads to the result 9. Another example can be given, of course:

Math.pow(5,3); > 125
That is, 5 cubed, or 5 × 5 × 5, is equal to 125.

ECMAScript 7 is the next version of JavaScript, in principle, we can use the new proposed exponentiation operator - * *, this form of notation may be more descriptive:

3 ** 2 > 9
On this moment Support for this operator is quite limited, so its use is not recommended.

The power function can be useful in the most different situations. A simple example, calculating the number of seconds in an hour: Math.pow (60,2).

Square and cube roots

Math.sqrt() and Math.cbrt() are the opposite of Math.pow(). As we remember, the square root of a is the number that gives a when squared.

Math.sqrt(9) > 3
At the same time, the cube root of a is a number that gives a when raised to a cube.

Math.cbrt(125) > 5
Math.cbrt() was only recently introduced into the JavaScript specification, and is therefore only supported in modern browsers: Chrome 38+, Firefox and Opera 25+, and Safari 7.1+. You will notice that Internet Explorer isn't on this list, but you'll find a polyfill on MDN.

Examples

Of course, we can use non-integer values ​​in one of these functions:

Math.pow(1.25, 2); > 1.5625 Math.cbrt(56.57) > 3.8387991760286138
Please note that this also works quite well when using negative argument values:

Math.pow(-5,2) > 25 Math.pow(10,-2) > 0.01
However, this won't work for square root:

Math.sqrt(-9) > NaN
From mathematical analysis we know that an imaginary number refers to the square roots of negative numbers. And this may lead us to another technique for working with complex numbers, but that's another story.

You can use fractions in Math.pow() to find the square and cube roots of numbers. Square root uses an exponent of 0.5:

Math.pow(5, 0.5); // = Math.sqrt(5) = 5 ** (1/2) > 2.23606797749979
However, due to the vagaries of floating point, you can't exactly guess the correct result:

Math.pow(2.23606797749979,2) > 5.000000000000001
In such situations, you will have to resort to cutting off signs from the number or rounding to some value.

Some people, for unknown reasons, in JavaScript confuse the Math.pow() function with Math.exp() , which is the exponential function for numbers in general. Note: in English language"exponent" is translated as "exponent", so this is more likely to apply to English speakers, although there are alternative names for exponent, such as index, power.

Mathematical constants

Working with mathematics in JavaScript is made easier by a number of built-in constants. These constants are properties of the Math object. It is worth noting that constants are written in uppercase, not CamelCase notation.

Only registered users can participate in the survey. , Please.

Tags: Add tags

I remind you that this introductory JavaScript course for beginners. Today we will look at what operators exist in JavaScript. Fasten seat belts! There will be a lot of bukaf.

When you have a bunch of data, you need to do something with it. The operators are busy with business. They are always adding, multiplying, dividing, subtracting, comparing, appropriating and whatever the hell they are doing. Without operators in programming you just can’t cook porridge.

The following types of operators are used in JavaScript:

  • Arithmetic operators
  • Assignment Operators
  • Comparison Operators
  • Logical operators
  • String operators
  • Conditional statements

This is far from full list, but for starters, this is enough for the eyes. Let's look at each type of operator presented, why they are needed and what they are used with. Go!

Arithmetic Operators in JavaScript

You have all been familiar with arithmetic operators since school. These are the usual addition, subtraction, division and multiplication signs: + , - , / , * . Accordingly, they perform the same functions in programming as in ordinary mathematics. You won't have any difficulties with this.

The data that operators work with is called operands.

2 + 3 // here the numbers 2 and 3 are the operands, and the + sign is the addition operator

As in mathematics, arithmetic operators have their own priorities: multiplication and division have higher priority than addition and subtraction.

2 + 3 * 4 // multiplication is performed here first, and only then addition

And just like in mathematics, parentheses are actively used to change the priority:

(2 + 3) * 4 // here the addition is performed first, and then the multiplication

By the way, the = sign is also an operator. As we already found out in the article about , this is an assignment operator, and not an equal sign at all. Don't forget about it!

Modulo division operator

Now let's look at more interesting arithmetic operators. And the first icon will be the percent icon - %. In JavaScript, these are not percentages of the word at all. This is how modulo division is denoted in programming. The result of such an operation will be the remainder of the division. For example:

100% 22 // the remainder will be 12
100% 10 // the remainder will be 0

In calculations, this operator has the same priority as multiplication and division, so don't forget to put parentheses.

Combining operators

The = operator can and should be combined with other operators to shorten the notation. Example:

var n = 2; // assign variable n the value 2
n = n + 3; // assign variable n a new value n + 2, get 5

The same thing can be written like this:

var n = 2;
n += 3; // equivalent to writing n = n + 3

Increment operators ++ and decrement – ​​–

Among the arithmetic operators there are a couple of very interesting ones - increment And decrement. They are designated ++ and ––, respectively. The first one increases the variable by one, and the second one decreases it. This feature is very often used in programming, as it provides a lot of convenience. Most often it can be found in conditional expressions, but more on that later.

Both operators have a specific location in the record. They can be like prefix form (before the variable) ++n , and in postfix(after the variable) n++ . The difference is huge! Never confuse these forms and remember them well. If these operators appear in front of a variable, then as a result they increase its value by 1. But! If they come after the variable, they return the original value. Example:

var n = 2, m = 0;
m = ++n // increases n by 1 (n = 3) and assigns m the same value as 3

var n = 2, m = 3;
m = n++ // increments n by 1 (n = 3), but sets m to previous value n = 2

I'm sure you can easily understand the first example. But with the second one there may be problems. To make it easier to understand this thing and not get confused, just imagine that you first assigned the value of variable n to variable m, and only after that increased the value of n by one. In the first example, you first increased the value of n by one, and then assigned this value to the variable m.

That's all for arithmetic operators. Of course, there are still a lot of variations and subtleties of using these simple operators, but this will be more than enough for you to get started.

Comparison Operators

And again we remember mathematics. The signs are familiar to everyone. In programming they are called comparison operators. JavaScript uses the following comparison operators:

< меньше
>more
<= меньше или равно
>= greater than or equal to
== equal
!= not equal
=== strictly equal
!== strictly not equal

Please note that the “greater than or equal” sign is written exactly like this >= , not => . That is, the arrow is placed before the equal sign, and not after it.

Comparison operators allow you to compare the values ​​of variables and the result of this operation is always the Boolean value true or false. They are usually used in conditional expressions. The result of the comparison determines which part of the code will be executed next.

In JavaScript you can compare different types data at the same time, for example, a number and a string:

12345 == "12345" // true

It's just that in this case the string is automatically converted to a number. Strict equality === or inequality!== are used only when comparing variables of the same type.

Logical operators

Logical operations in JavaScript is one of the rather tricky topics for beginners. It’s worth understanding it thoroughly in order to successfully move forward in mastering the language. They are most often used in conjunction with comparison operators and produce a Boolean value of true or false .

There are three logical operators:

&& (AND)
|| (OR)
! (NOT)

Logical operator && (AND)

The && operator performs a logical AND operation on two values. However, it returns true if and only if both operands evaluate to true . If one or both operands are false, then the operator returns false. Examples:

2 < 3 && 4 < 5 // true
2 < 3 && 5 < 4 // false
3 < 2 && 5 < 4 // false

Logical operators have lower precedence than comparison operators, so in the examples given we do without parentheses. It is clear that first we compare numbers with each other, and only then apply logic.

Logical operator || (OR)

With the logical operator || (OR) another song. Operator || performs a logical OR operation on two operands. If one or both operands have true meaning, it returns true. If both operands are false, it returns false. Examples:

2 < 3 || 4 < 5 // true
2 < 3 || 5 < 4 // true
3 < 2 || 5 < 4 // false

Logical operators have a trick. They don't like extra work. As do I, by the way. They always start their calculations from left to right. And if the first part of the expression matches their conditions, then they don’t even evaluate the rest of the expression.

For example, if the operator || finds the true value at the very beginning, it immediately gives the true value, and does not check the rest. Also, the && operator, if it finds a false expression at the very beginning, then immediately gives a false result, and does not check the rest of the expression.

And one more trick: the priority of the AND operator && is greater than that of OR || so it executes earlier:

2 < 3 || 4 < 5 && 5 < 6 // здесь сначала будет выполнено вычисление в правой части, а потом уже в левой

Logical operator! (NOT)

Logical operator! stands for "logical NOT". It is used with only one operand and reverses the value of that operand. If n is true, then!n will be false. Since this operator can be attached to only one operand, to invert the whole expression, it must be placed in parentheses!(n && m) .

String operators

We already talked about string operators earlier. This is the same plus + that is used to connect string variables, or otherwise - for concatenation(addition of strings). Example:

"Igor" + "Quentor" == "Igor Quentor"

Note that the first word has a space added before the closing quotation mark. If you do not add it, the lines will merge into one word “IgorQuentor”.

This operator has one feature: if the expression contains at least one string, then it and all other arguments convert to the string type. For example:

The remaining arithmetic operators work only with numbers and always reduce their arguments to a number.

Conditional statements

In JavaScript there are two conditional operators if and?: Although, to be precise, if is actually a control instruction and quite extensive, with a bunch of goodies and interesting features. Therefore, there will be a separate article about it. For now, let's look at a simpler conditional operator?:

Usually this operator is written as?: But in programs it looks different. It has three operands. Does the first operand precede the character? , the second one is between the characters? and: third - after:

condition? value 1: value 2

The meaning of its operation is simple: if the set condition is met, then the value 1 is returned, but if not, the value 2. This conditional operator often serves as a simpler replacement for the if statement, when the latter is not particularly necessary. At the same time, the record itself is shortened and easier to read.

That's all for now!

I hope you now understand a little about operators in JavaScript. And so that your brain doesn’t boil, here’s a short cartoon for you to relax - A programmer can do anything! :)