Arithmetic operators in JavaScript. Arithmetic operators Round down to the nearest integer

Having talked about priorities, associativity and other minor issues, we can begin to discuss the operators themselves. This section provides descriptions of arithmetic operators:

Addition (+)
The plus operator adds numeric operands or performs string concatenation. If one of the operands is a string, the other operand is converted to a string and concatenation is performed. The object's operands are converted to numbers or strings, which can be added or concatenated. The conversion is done using the valueOf() and/or toString() methods.

Subtraction (−)
When minus is used as a binary operator, it subtracts the second operand from the first. If non-numeric operands are specified, it attempts to convert them to numbers.

Multiplication (*)
The * operator multiplies its two operands. It tries to convert non-numeric operands to numbers.

Division (/)
The / operator divides the first operand by the second. Attempts to convert non-numeric operands to numbers. Those accustomed to programming languages ​​that distinguish between integers and real numbers may expect to obtain an integer result when dividing one integer by another.

However, in JavaScript, all numbers are real, so all divisions produce a floating point result. The operation 5/2 gives 2.5, not 2. Dividing by zero gives plus or minutes infinity as the result, and 0/0 gives NaN.

Modulo division (%)
The % operator calculates the remainder obtained when the first operand is integer divided by the second. If non-numeric operands are given, the operator attempts to convert them to numbers. The sign of the result matches the sign of the first operand. For example, 5% 2 gives 1.
The modulo division operator is usually used with integer operands, but it also works for real values. For example, -4.3% 2.1 gives a result of -0.1.

Unary minus (−)
When minus is used as a unary operator before a single operand, it performs a unary sign change operation. In other words, it converts a positive value to a negative value and vice versa. If the operand is not a number, this operator attempts to convert it to a number.

Unary plus (+)
For symmetry with the unary minus operator, JavaScript also has a unary plus operator. You can use this operator to explicitly specify the sign of numeric literals if you think this will make the program text more understandable:
var profit = +1000000;

In such code, the plus operator does nothing; the result of his work is the meaning of his argument.

However, it converts non-numeric arguments to numbers. If the argument cannot be converted, NaN is returned.

Increment (++)
This operator increments (that is, increases by one) its single operand, which must be a variable, array element, or object property. If the value of this variable, array element, or property is not a number, the operator first tries to convert it to a number. The exact behavior of this operator depends on its position with respect to the operand. If you put it before the operand (prefix increment operator), then 1 is added to the operand, and the result is the incremented value of the operand. If it is placed after the operand (postfix increment operator), then 1 is added to the operand, but the result is the original value of the operand. If the value being incremented is not a number, it is converted to a number during the calculation process.

For example, the following code sets the variables i and j to 2:
i = 1;
j = ++i;
And this one sets i to 2 and j to 1:
i = 1;
j = i++;

This operator, in both of its forms, is most often used to increment the counter that controls the loop.

Note that you cannot insert a newline between a prefix or postfix increment operator and its preceding operand, since semicolons are inserted automatically in JavaScript. If you do this, JavaScript will treat the operand as a full instruction and insert a semicolon after it.

Decrement (−−)
This operator decrements (that is, decreases by 1) its single numeric operand, which can be a variable, an array element, or an object property. If the value of this variable, element, or property is not a number, the operator first tries to convert it to a number. As with the ++ operator, the exact behavior of the - operator depends on its position relative to its operand. When placed before an operand, it decrements the operand and returns the decremented value. After the operand, it decrements the operand but returns the original value.

The operators: - (subtraction), + (addition), * (multiplication) and / (division) work exactly the same as arithmetic operations in mathematics. The % 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

The ** (exponentiation) operator 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 increments 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, the original value of the operand is first returned, and only then the value of the operand is incremented by one.

Mathematical operations are one of the most basic and universal functions of any programming language. In JavaScript, numbers are often used in common tasks such as determining the size of a browser window, calculating the final price of a monetary transaction, or the distance between elements in a website document.

You don't need to be good at math to be a good developer, but it is important to know what types of operations are available in JavaScript and how to use them to perform practical tasks.

Unlike other programming languages, JavaScript only has one numeric data type; it doesn't distinguish between integers and floats.

This tutorial will cover arithmetic operators, assignment operators, and order of operations with JavaScript numeric data.

Arithmetic operators

Arithmetic operators are symbols that define mathematical operations and return a result. For example, in 3 + 7 = 10, the symbol + defines the syntax for the addition operation.

Many JavaScript operators are familiar to you from basic mathematics, but there are also several additional operators.

All JavaScript arithmetic operators are presented in the following table.

Operator Syntax Example Definition
Addition + x+y Sum of x and y
Subtraction x - y Difference between x and y
Multiplication * x*y Derivative of x and y
Division / x/y Quotient of x and y
Module % x % y Remainder x/y
Exponentiation ** x**y x to the power of y
Increment ++ x++ x plus one
Decrement x— x minus one
Addition and subtraction

Addition and subtraction operators are available in JavaScript and can be used to find the sum and difference of numeric values. JavaScript has a built-in calculator, and mathematical operations can be performed directly in the console.

The plus sign allows you to add numbers, for example:

In addition to operations with prime numbers, JavaScript allows you to assign numbers to variables and perform calculations on them. For example, you can assign numeric values ​​to the variables x and y, and put the result in z.

// Assign values ​​to x and y
let x = 10;
let y = 20;
//Add x and y and assign the sum to z
let z = x + y;
console.log(z);
30

// Assign values ​​to x and y
let x = 10;
let y = 20;
// Subtract x from y and assign the difference to z
let z = y - x;
console.log(z);
10

// Assign values ​​to x and y
let x = -5.2;
let y = 2.5;
// Subtract y from x and assign the difference to z
let z = x - y;
console.log(z);
-7.7

One interesting feature in JavaScript that you should consider and know is the result of adding a number and a string. We know that 1 + 1 must equal 2, but this equation will give an unexpected result.

let x = 1 + "1";
console.log(x);
typeof x;
11
"string"

Instead of adding numbers, JavaScript converts the entire expression into strings and concatenates them. It's important to be careful with dynamic typing in JavaScript because it can have undesirable results.

Addition and subtraction in JavaScript are often used to scroll the navigation bar.

function scrollToId() (
const navHeight = 60;
window.scrollTo(0, window.pageYOffset - navHeight);
}
window.addEventListener("hashchange", scrollToId);

In this case, the panel will scroll 60 pixels from the id.

Multiplication and division

JavaScript multiplication and division operators are used to find the derivative and quotient of numeric values.

The asterisk is the multiplication operator.

// Assign values ​​to x and y
let x = 20;
let y = 5;
// Multiply x by y to get the product
let z = x * y;
console.log(z);
100

Multiplication can be used to calculate the price of an item after sales tax has been imposed.

const price = 26.5; // Price of item before tax
const taxRate = 0.082; // 8.2% tax rate
// Calculate total after tax to two decimal places
let totalPrice = price + (price * taxRate);
totalPrice.toFixed(2);
console.log("Total:", totalPrice);
Total: 28.67

Slash is the division operator.

// Assign values ​​to x and y
let x = 20;
let y = 5;
// Divide y into x to get the quote
let z = x / y;
console.log(z);
4

Division is especially useful when calculating time, such as calculating the number of hours or percentage correct on a test.

The absolute value of a number

Modulus is another arithmetic operator, less popular than the previous ones. Represented by the % symbol. It returns the remainder when the first number is divided by the second.

For example, we know that 9 is divisible by 3 without a remainder:

The number modulus allows you to determine whether a number is even or odd, for example:

// Initialize function to test if a number is even
const isEven = x => (
// If the remainder after dividing by two is 0, return true
if (x % 2 === 0) (
return true;
}
// If the number is odd, return false
return false;
}
// Test the number
isEven(12);
true

In this example, 12 is divisible by 2, so it is an even number.

In programming, the number modulus is often used in combination with conditional statements.

Exponentiation

Exponentiation is one of the newest operators in JavaScript. The syntax for exponentiation is two asterisks in a row (**).

For example, 10 to the fifth power (10^5) is written like this:

10 ** 5;
100000

The operation 10**5 has the same result as 10*10 repeated 5 times.

10 * 10 * 10 * 10 * 10;

This operation can also be written using the Math.pow() method.

Math.pow(10, 5);
100000

Using the exponentiation operator is a quick way to determine the power of a given number, but as always, when choosing between a method and an operator, it is important to be consistent and code in the same style.

Increment and decrement

The increment and decrement operators increase or decrease the numeric value of a variable by one. They are represented by two plus signs (++) or two minuses (-) and are often used in loops.

Please note that the increment and decrement operators can only be used with variables. Trying to use them with prime numbers will result in an error.

7++
Uncaught ReferenceError: Invalid left-hand side expression in postfix operation

The increment and decrement operators can be classified as prefix and postfix operators, depending on where the operator is placed in relation to the variable.

The prefix increment is written as ++x.

//Set a variable
let x = 7;

let prefix = ++x;
console.log(prefix);
8

The value of x has increased by 1. The postfix increment is written as y++.

//Set a variable
let y = 7;
// Use the prefix increment operation
let postfix = y++;
console.log(postfix);
7

The postfix operation did not increment the value. This value will not be incremented until the expression is evaluated. To do this, you need to run the operation twice:

let y = 7;
y++;
y++;
console.log(y);
8

Most often these operators are found in loops. In this for loop, the for statement is executed 10 times, starting from 0.

// Run a loop ten times
for (let i = 0; i< 10; i++) {
console.log(i);
}
0
1
2
3
4
5
6
7
8
9

In this example, the loop is iterated using the increment operator.

Simply put, x++ can be thought of as short for x = x + 1, and x can be thought of as short for x = x – 1.

Assignment Operators

One of the most commonly used operators is the assignment operator, which we have already seen in this tutorial. It is represented by an equal sign (=). The = symbol is used to assign the value on the right to the variable on the left.

// Assign 27 to age variable
let age = 27;

In addition to the standard assignment operator, JavaScript has compound assignment operators, which combine the arithmetic operator with the = operator.

For example, the add operator will start from the original value and add a new value to it.

// Assign 27 to age variable
let age = 27;
age += 3;
console.log(age);
30

Essentially, age += 3 is the same as age = age + 3.

All arithmetic operators can be combined with an assignment operator. Below is a reference table of assignment operators in JavaScript.

Compound assignment operators are often used in loops, like increments and decrements.

Operator precedence

Operators are executed in order of priority, just like in ordinary mathematics.

For example, multiplication has higher priority than addition.

// First multiply 3 by 5, then add 10
10 + 3 * 5;
25

If you need to perform an addition operation first, put it in parentheses - such operations always have the highest priority.

// First add 10 and 3, then multiply by 5
(10 + 3) * 5;
65

Below you will find a table of precedence of arithmetic operators in JavaScript. For increment and decrement, the postfix has higher priority than the prefix.

Increment/decrement, multiplication/division and addition/subtraction have the same priority level.

Not only arithmetic operators have priority, but also assignment operators, logical operators, conditional operators, etc. You can see the full list.

Tags:

Last update: 11/1/2015

Mathematical operations

JavaScript supports all basic math operations:

Addition:

Var x = 10; var y = x + 50;

Subtraction:

Var x = 100; var y = x - 50;

Multiplication :

Var x = 4; var y = 5; var z = x * y;

Division:

Var x = 40; var y = 5; var z = x / y;

Modulo division (the %) operator returns the remainder of the division:

Var x = 40; var y = 7; var z = x % y; console.log(z); // 5

The result will be 5, since the largest integer that is less than or equal to 40 and is divisible by 7 is 35, and 40 - 35 = 5.

Increment:

Var x = 5; x++; // x = 6

The increment operator ++ increments a variable by one. There is a prefix increment that first increments a variable by one and then returns its value. And there is a postfix increment, which first returns the value of the variable and then increments it by one:

// prefix increment var x = 5; var z = ++x; console.log(x); // 6 console.log(z); // 6 // postfix increment var a = 5; var b = a++; console.log(a); // 6 console.log(b); // 5

Postfix increment is similar to the operation:

A = a + 1; // a++

A decrement decreases the value of a variable by one. There is also a prefix and postfix decrement:

// prefix decrement var x = 5; var z = --x; console.log(x); // 4 console.log(z); // 4 // postfix decrement var a = 5; var b = a--; console.log(a); // 4 console.log(b); // 5

As is customary in mathematics, all operations are performed from left to right and differ in priority: first, increment and decrement operations are performed, then multiplication and division are performed, and then addition and subtraction. To change the standard flow of operations, part of the expressions can be placed in brackets:

Var x = 10; var y = 5 + (6 - 2) * --x; console.log(y); //41

Assignment Operators

    Equates a specific value to a variable: var x = 5;

    Addition followed by assignment of the result. For example:

    Var a = 23; a += 5; // similar to a = a + 5 console.log(a); // 28

    Subtraction followed by assignment of the result. For example:

    Var a = 28; a -= 10; // similar to a = a - 10 console.log(a); // 18

    Multiplication followed by assignment of the result:

    Var x = 20; x *= 2; // similar to x = x * 2 console.log(x); // 40

    Division followed by assignment of the result:

    Var x = 40; x /= 4; // similar to x = x / 4 console.log(x); // 10

    Obtaining the remainder of a division and then assigning the result:

    Var x = 10; x %= 3; // similar to x = x % 3 console.log(x); // 1, since 10 - 3*3 = 1

Comparison Operators

Typically, comparison operators are used to test conditions. Comparison operators compare two values ​​and return true or false:

    The equality operator compares two values, and if they are equal, returns true, otherwise returns false: x == 5

    The identity operator also compares two values ​​and their type, and if they are equal, returns true, otherwise returns false: x === 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: x != 5

    Compares two values ​​and their types, and if they are not equal, returns true, otherwise returns false: x !== 5

    Compares two values, and if the first is greater than the second, then returns true, otherwise returns false: x > 5

    Compares two values, and if the first is less than the second, then returns true, otherwise returns false: x< 5

    Compares two values, and if the first is greater than or equal to the second, then returns true, otherwise returns false: x >= 5

    Compares two values, and if the first is less than or equal to the second, then returns true, otherwise returns false: x 50 && percent< 12; console.log(result); //true

    Returns true if at least one comparison operation returns true, otherwise returns false:

    Var income = 100; var isDeposit = true; var result = income > 50 || isDeposit == true; console.log(result); //true

    Returns true if the comparison operation returns false:

    Var income = 100; var result1 = !(income > 50); console.log(result1); // false, since income > 50 returns true var isDeposit = false; var result2 = !isDeposit; console.log(result2); // true

String Operations

Strings can use the + operator to concatenate. For example:

Var name = "Volume"; var surname = "Sawyer" var fullname = name + " " + surname; console.log(fullname); //Tom Sawyer

If one of the expressions represents a string and the other represents a number, then the number is converted to a string and the string concatenation operation is performed:

Var name = "Volume"; var fullname = name + 256; console.log(fullname); //Volume256

At the end we will write a small program that will demonstrate working with operations on variables. To do this, we define the following web page index.html:

JavaScript var sum = 500; // deposit amount var percent = 10; // interest on deposit var income = sum * percent / 100; // income on deposit sum = sum + income; // determine the new amount console.log("Deposit income: " + income); console.log("Deposit amount after the first year: " + sum);

The script declares three variables: sum, percent and income. The income variable is calculated from the other two variables using multiplication and division operations. And at the end, its value is summed with the value of the sum variable.


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 of 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)) // get three messages: 2, 1, 2

JavaScript's set of mathematical 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 it will be very difficult to achieve high performance.