Operator precedence in JavaScript. JavaScript: Operators Increment and Decrement Operators

Math operations are some of the most basic and versatile functions of any programming language. In JavaScript, numbers are often used in general tasks such as sizing a browser window, calculating the final price of a money transaction, or the distance between elements in a site document.

You don't need to have high math skills to be a good developer, but it’s important to know what types of operations are available in JavaScript and how to use them to accomplish practical tasks.

Unlike other programming languages, JavaScript has only one numeric data type; it does not separate integers and floating point numbers.

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

Arithmetic operators

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

Many JavaScript operators are familiar to you from basic math, but there are a few additional operators as well.

All JavaScript arithmetic operators are shown 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 Private 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

The 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 math operations can be performed directly in the console.

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

In addition to manipulating prime numbers, JavaScript allows you to assign numbers to variables and perform calculations on them. For example, you can assign numeric values \u200b\u200bto variables x and y, and place the result in z.

// Assign values \u200b\u200bto x and y
let x \u003d 10;
let y \u003d 20;
// Add x and y and assign the sum to z
let z \u003d x + y;
console.log (z);
30

// Assign values \u200b\u200bto x and y
let x \u003d 10;
let y \u003d 20;
// Subtract x from y and assign the difference to z
let z \u003d y - x;
console.log (z);
10

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

There is one interesting feature in JavaScript to keep in mind and be aware of is the result of adding a number and a string. We know that 1 + 1 should equal 2, but this equation will give unexpected results.

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

Instead of adding numbers, JavaScript converts the entire expression to strings and concatenates them. It's important to be careful with JavaScript dynamically typing as it can have unwanted results.

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

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

In this case, the panel will scroll 60 pixels from 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 \u200b\u200bto x and y
let x \u003d 20;
let y \u003d 5;
// Multiply x by y to get the product
let z \u003d x * y;
console.log (z);
100

Multiplication can be used to calculate the price of an item after the introduction of sales tax.

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

Slash is the division operator.

// Assign values \u200b\u200bto x and y
let x \u003d 20;
let y \u003d 5;
// Divide y into x to get the quotient
let z \u003d x / y;
console.log (z);
4

Division is especially useful when calculating time, for example, when calculating the number of hours or the percentage of correct answers in a test.

The absolute value of a number

Module is another arithmetic operator, less popular than the previous ones. Represented by% 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 remainder:

The number module allows you to define an even or odd number, for example:

// Initialize function to test if a number is even
const isEven \u003d x \u003d\u003e (
// If the remainder after dividing by two is 0, return true
if (x% 2 \u003d\u003d\u003d 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 this is an even number.

In programming, the number unit is often used in conjunction with conditional statements.

Exponentiation

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

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

10 ** 5;
100000

Operation 10 ** 5 has the same result as 10 * 10 repeated 5 times.

10 * 10 * 10 * 10 * 10;

You can also write this operation using the Math.pow () method.

Math.pow (10, 5);
100000

Using the exponentiation operator is a quick way to determine the exponent of a given number, but, as usual, when choosing between method and operator, it is important to be consistent and write 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 pluses (++) or two minuses (-) and are often used in loops.

Note: 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 operations, depending on where the operator is placed in relation to the variable.

The prefix increment is written as ++ x.

// Set a variable
let x \u003d 7;

let prefix \u003d ++ 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 \u003d 7;
// Use the prefix increment operation
let postfix \u003d y ++;
console.log (postfix);
7

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

let y \u003d 7;
y ++;
y ++;
console.log (y);
8

These operators are most often found in loops. In this for loop, the statement is run 10 times, starting at 0.

// Run a loop ten times
for (let i \u003d 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 an abbreviation for x \u003d x + 1, and x as an abbreviation for x \u003d x - 1.

Assignment operators

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

// Assign 27 to age variable
let age \u003d 27;

In addition to the standard assignment operator, JavaScript has compound assignment operators that combine the arithmetic operator with the \u003d operator.

For example, the add statement will start at the original value and add a new value to it.

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

Basically, age + \u003d 3 is the same as age \u003d age + 3.

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

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

Operator priority

Operators are executed in order of precedence, just like in normal mathematics.

For example, multiplication takes precedence over addition.

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

If you need to perform an addition operation first, enclose 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, postfix takes precedence over prefix.

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

Priority is given not only to arithmetic operators, but also to assignment operators, logical operators, conditional operators, etc. The full list can be viewed.

Tags:

The JavaScript language supports the principles of object-oriented programming. All objects that you can meet in work can be divided into three large groups:

1. Built-in language objects. These objects are designed to work with specific data types or perform common tasks (for example, Math, String, Date objects, etc.). Before using built-in objects, it is often necessary to create an appropriate instance of this object (except for Math).

2. External standard objects. Designed to interact with standard interface elements and browser functions. These are objects such as window, document and event. All external objects are available anywhere in the script and do not require instantiation.

3. Custom objects. Created by the developer for some specific needs. Creating your own objects requires certain skills and development experience.

Any object contains properties and methods. An object property is some kind of quantitative or qualitative parameter that determines the characteristics of an object. An object method sets some action that a given object can perform. If we digress from programming and consider an ordinary person as an object, then its properties will be "height", "weight", "eye color", and the methods will be "eat", "drink", "walk", etc.

You can refer to a property or method by specifying their name and object instance:

object.property

object.method ()

This notation (through a period) allows you to uniquely identify an instance of an object whose properties and methods you want to use. In practice, properties are used just like regular variables, and methods are used like regular functions. Note that the method name must always end in parentheses, even if you don't pass any parameters to the method. For example:

// the interpreter will call the open () METHOD

// interpreter will look for PROPERTY open,

// won't find it and throw an error

8. Special operators in JavaScript.

?: Allows you to do a simple "if ... then ... else"

Evaluates two expressions and returns the result of the second expression.

delete Allows you to delete an object property or element at a specific index in an array.

new Allows you to create a sample of a user-defined object type or one of the built-in object types.

this A keyword that you can use to refer to the current object.

typeof Returns a string indicating the type of the unvalued operand.

void The void operator defines an expression that will be evaluated without returning a value.

9. Operator Priorities in JavaScript.

Operator seniority

Operation precedence is the order in which operations are performed in complex expressions. Operations at the same level have equal seniority. Calculations are performed from left to right for all binary operations, starting with the operations listed at the top of the list and ending with the operations at the bottom.

The seniority of operators, from lowest to highest, will be as follows:

Assignment \u003d + \u003d - \u003d * \u003d / \u003d% \u003d<<=>>=>>>=&=^=|=

Conditional selection? :

Logical OR ||

Boolean AND &&

Bitwise OR |

Bitwise exclusive ^

Bitwise AND &

Inequality! \u003d

Equality / Inequality \u003d\u003d! \u003d

Comparison<<=>> =

Bit shift<< >> >>>

Addition / Subtraction + -

Multiply / divide * /%

Negation / complement / unary minus / increment / decrement! ~ - ++ -

Calling, passing parameters ().

Operator seniority

Operation precedence is the order in which operations are performed in complex expressions. Operations at the same level have equal seniority. Calculations are performed from left to right for all binary operations, starting with the operations listed at the top of the list and ending with the operations at the bottom.

The seniority of operators, from lowest to highest, will be as follows:

Assignment \u003d + \u003d - \u003d * \u003d / \u003d% \u003d<<=>>=>>>=&=^=|=

Conditional selection? :

Logical OR ||

Boolean AND &&

Bitwise OR |

Bitwise exclusive ^

Bitwise AND &

Inequality! \u003d

Equality / Inequality \u003d\u003d! \u003d

Comparison<<=>> =

Bit shift<<>>>>>

Addition / Subtraction + -

Multiply / divide * /%

Negation / complement / unary minus / increment / decrement! ~ - ++ -

Calling, passing parameters ().

Reserved keywords in JavaScript.

JavaScript has a number of reserved keywords. These words are of three types: JavaScript reserved words, reserved words for the future, and words to avoid. JavaScript keywords

break false in this void

continue for new true while

delete function null typeof with

else if return var

JavaScript keywords for future use

case debugger export super

catch default extends switch

class do finally throw

const enum import try

Words to avoid using are those that already have the names of JavaScript internal objects or functions. This includes words like String or parseInt.

Using any keyword from the first two categories will result in a compile-time error when your program is loaded. Using reserved words from the third list can lead to misbehavior problems if you try to use your variables and original primitives with the same name in the same program. For example, the following program will not do what you want:

var text \u003d new String ("This is a string object");

In this case, you will receive an error stating that String is not an object. Many use cases for a pre-existing identifier are not all that clear.

Scripts. Creation of scripts.

JavaScript is a scripting (scripting) language used primarily for creating interactive elements on Web pages. It can be used to build menus, validate forms, change images, or do anything else that you can do on a Web page. If you look at GoogleMaps or Google's GMail service, you can see what JavaScript is capable of today.

Since JavaScript is currently the only scripting language supported by all major Web browsers (InternetExplorer, Firefox, Netscape, Safari, Opera, Camino, etc.), it is widely used.

JavaScript code is usually executed by the client's Web browser, in which case it is called client-side scripting. However, JavaScript can also be executed on a Web server to generate HTML documents, thereby rendering server-side scripting. While JavaScript is usually limited to client-side scripting, it is also a very powerful server-side language.

When writing JavaScript code, you actually only need a text editor and a Web browser. Knowledge of HTML and CSS will definitely play a positive role, and if you want to use JavaScript skills on a website, you will also need a website. If you already have a website, great! If not, there are many free servers that you can use to host your pages.

As for the text editor, Windows has a NotePad editor. While this will be sufficient for editing JavaScript, HTML, and CSS, a more powerful editor such as EditPlus or another may be more convenient.

Well, now you can move on to creating JavaScript!

First, you need to learn how to add JavaScript to your HTML page. You can do this in one of two ways: place Script tags on a Web page and place JavaScript within those tags, or place all JavaScript code in a separate file and link to it using a Script tag.

Any of these methods are perfectly valid, but they have different purposes. If you have small code that will only be used on one page, then placing it between Script tags is a good solution. If, however, you have a large piece of code that will be used across multiple pages, then it’s probably better to put that JavaScript code in a separate file and link to it. This is done so that you do not need to load this code every time you visit various pages. The code is loaded once and the browser saves it for later use. This is similar to how Cascading Style Sheets (CSS) are used.

Below are examples of two ways to connect JavaScript code:

Scripting functions.

You can style the source code snippets as a function by calling this function as needed from various places in JavaScript.

Typically, functions are defined in the head section of an HTML document, marked with tags and... As we said, the function must be defined before being called. Placing all function definitions in the header section of an HTML document ensures that those functions are available when the document is processed.

The general view of the function definition is presented below:

function name ([parameter 1] [, parameter 2] [..., parameter N])

function body lines

All parameters are passed to the function by value. Therefore, the function cannot change the contents of the variables passed to it as parameters.

With the return keyword, a function can return a value.

JavaScript expressions 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 data being processed. For example, operands of different types are involved in comparison operations, but the returned result will always be of the Boolean type.

Figure: 1. The structure of an expression in JavaScript

Operands Is data processed by JavaScript. The operands can be both simple data types and complex ones, as well as other expressions.

Operators Are symbols of the language that perform various operations with data. Operators can be written using punctuation symbols or keywords.

The following types of operators are distinguished depending on the number of operands:
unary - one operand is involved in the operation;
binary - two operands are involved in the operation;
ternary - combines three operands.

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

Expressions and Operators in JavaScript

1. Arithmetic operators

Arithmetic operators are designed to perform mathematical operations, they operate on numeric operands (or variables that store numeric values), returning a numeric value as the 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 corresponding operation. If the type conversion is not possible, the result will be NaN (not a number).

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

2. Assignment operators

Assignment operators are used to assign values \u200b\u200bto variables. Combined operators allow you to store the original and subsequent values \u200b\u200bin one variable.

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

3. Operators of increment and decrement

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

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

4. Comparison operators

Comparison Operators are used to match operands, the expression can result in one of two values \u200b\u200b- true or false. Operands can be not only numbers, but also strings, booleans, and objects. However, comparison can only be performed for 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 / is converted to a string and the other is a number / is converted to a number, then the operator will try 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 comparison is false.

Comparison operations are most often used when organizing branches in programs.

Table 4. Comparison operators
Operator / Operation Description Priority
\u003d\u003d Equality Tests for a match between two values, allowing for type conversion. Returns true if the operands are the same and false if they are different. 9
! \u003d Inequality Returns true if the operands are not equal 9
\u003d\u003d\u003d Identity Tests two operands for "identity" using a strict match definition. Returns true if the operands are equal without type conversion. 9
! \u003d\u003d Non-identity Performs an identity check. Returns true if the operands are not equal without type conversion. 9
\u003e More Returns true if the first operand is greater than the second, otherwise returns false. 10
\u003e \u003d Greater than or equal Returns true if the first operand is at least 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 \u003d\u003d "5"; // will return true 5! \u003d -5.0; // will return true 5 \u003d\u003d\u003d "5"; // returns false false \u003d\u003d\u003d false; // will return true 1! \u003d\u003d true; // will return true 1! \u003d true; // will return false as true converts to 1 3\u003e -3; // will return true 3\u003e \u003d "4"; // will return false

5. Logical operators

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

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

6. Bitwise operators

Bitwise operators treat operands as a 32-bit sequence of zeros and ones and return a numeric value representing the result of the operation, written in decimal notation. Integers are considered as operands, the fractional part of the operand is discarded. Bitwise operations can be used, for example, when encrypting data, to work with flags, and to differentiate access rights.

Table 6. Bitwise operators
Operator / Operation Description 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 1 at position, the result will also contain 1 at that position, otherwise the result at this position will be 0. 6
^ Exclusive OR If one and only one value contains 1 in any position, then the result will also contain 1 in this position, otherwise the result in this position will be 0. 7
~ Denial A bitwise negation operation is performed on the binary representation of the expression value. Any position containing 1 in the original expression is replaced with 0. Any position containing 0 in the original expression becomes 0. Positive numbers start at 0, negative numbers start at -1, so ~ n \u003d\u003d - (n + 1). 14
The operator shifts the bits of the first operand to the left by the number of bit positions set by the second operand. Zeros are used to fill the positions on the right. Returns a result of the same type as the left operand. 11
\u003e\u003e 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 out of range are deleted. 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 one position is equivalent to dividing by 2 (discarding the remainder), and shifting to the right two positions is equivalent to dividing by 4, and so on. 11
\u003e\u003e\u003e Bitwise shift right 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 appended to the left regardless of the sign of the first operand. Digits shifted out of range are deleted. 11
var x \u003d 9, y \u003d 5, z \u003d 2, s \u003d -5, result; // 9 is equivalent to 1001, 5 is equivalent to 0101 result \u003d x & y; // will return 1 (equivalent to 0001) result \u003d x | y; // will return 13 (equivalent to 1101) result \u003d x ^ y; // will return 12 (equivalent to 1100) result \u003d ~ y; // will return -6 (equivalent to 1100) result \u003d x<< y; // вернет 288 (эквивалентно 100100000) result = x >\u003e z; // will return 2 (equivalent to 10) result \u003d s \u003e\u003e\u003e z; // will return 1073741822 (equivalent to 111111111111111111111111111110)

7. String operators

There are several operators that work with strings in a special way.

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

8. Special operators

Table 8. Special operators
Operator / Operation Description Priority
... Accessing a property Access a property of an object. 15
, Multiple computation Evaluates multiple independent expressions on a single line. 1
Array indexing Access the elements of an array or properties of an object. 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 Object type check The operator checks if an object is an instance of a specific 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 specified on the left is an instance of the class specified on the right; otherwise, false. 10
in Checking if a property exists The left operand must be a string, and the right must be an array or object. If the left value is a property of an object, the result will be true. 10
new Object creation The operator creates a new object with undefined properties, then calls the constructor function to initialize it (pass 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, otherwise false. Removing an array element does not change its length. 14
void Defining an expression with no return value Unary operator, discards the value of the operand and returns underfined. 14
?: Conditional expression operation Ternary operator, allows you to organize simple branching. There are three operands involved in the expression, the first must be a Boolean value or be converted to it, 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 third. 3
document.write ("hello world"); // displays the string hello world i \u003d 0, j \u003d 1; // stores values \u200b\u200bin variables function1 (10, 5); // call the function function1 with parameters 10 and 5 var year \u003d; // creates an array with elements typeof (a: 1); // will return "object" var d \u003d new Date (); // create a new object using the Date () constructor d instanceof Date; // will return true var mycar \u003d (make: "Honda", model: "Accord", year: 2005); "make" in mycar; // will return true var obj \u003d new Object (); // creates an empty object var food \u003d ["milk", "bread", "meat", "olive oil", "cheese"]; delete food; // removes the fourth element from food x\u003e 10? x * 2: x / 2; // returns the value x * 2 if x\u003e 10, otherwise x / 2

9. JavaScript comments

Single line comment: precede the comment text with // characters.

An operator is a character (s) or keyword that makes some kind of calculation that involves one or more values. The values \u200b\u200bto the left and right of the operator are called operands. An operator with one operand is called unary, with two - binary, with three - ternary.

Operators can automatically convert the types of their operands as needed. For example, the multiplication operator * expects numbers, so the expression "2" * "3" is considered perfectly valid because the interpreter will implicitly convert strings to numbers.

Operator priority

Operator priority is a property of an operator that affects the order of its execution in an expression with several different operators in the absence of an explicit indication of the order of their evaluation. Higher priority statements run before lower priority statements.

In the Operator column, the three dots indicate the location of the operands relative to the operator.

Column A indicates the associativity of the operator. Associativity is the order in which operators with the same precedence are processed. For example, the subtraction operator has left-to-right associativity, so the following two expressions are equivalent:

X - y - z (x - y) - z

The assignment operator is right-to-left associative, so the following two expressions are equivalent:

W \u003d x \u003d y \u003d z w \u003d (x \u003d (y \u003d z))

Column O indicates the number of operands.

In the Value Types column, the expected operand types are indicated before the arrow, and the return type after the arrow.

lval (short for left value) is a left-sided expression. It is a historical term for an expression that may appear to the left of an assignment operator. Left-hand side expressions are: variables, object properties, and array elements.

The table below lists the operators in decreasing order of priority, with horizontal lines separating groups of operators with different priority levels.

Operator Operator type AND ABOUT Value types
(…) Grouping is absent
1 any → any
… . …
… […]
new ... ()
Access operator
Access operator
new (with a list of arguments)
from left to right
from left to right
is absent
2
2
1
lval, lval -\u003e any
lval, string or number -\u003e any
constructor -\u003e object
… ()
new ...
Function call
new (no arguments)
from left to right
from right to left
1
1
function -\u003e any
constructor -\u003e object
… ++
… --
Postfix increment
Postfix decrement
is absent
is absent
1
1
lval -\u003e number
lval -\u003e number
! …
~ …
+ …
- …
++ …
-- …
delete ...
typeof ...
void ...
Logical NOT (inversion)
Bitwise NOT (inversion)
Unary plus
Unary minus
Prefix increment
Prefix decrement
Deleting
Defines the data type
Returning an undefined value
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
1
1
1
1
1
1
1
1
1
any -\u003e boolean
whole → whole
number -\u003e number
number -\u003e number
lval -\u003e number
lval -\u003e number
lval -\u003e boolean
any -\u003e string
any -\u003e undefined
… ** …
… * …
… / …
… % …
Exponentiation
Multiplication
Division
Division with remainder
from right to left
from left to right
from left to right
from left to right
2
2
2
2
number, number -\u003e number
number, number -\u003e number
number, number -\u003e number
number, number -\u003e number
… + …
… - …
… + …
Addition
Subtraction
Concatenation
from left to right
from left to right
from left to right
2
2
2
number, number -\u003e number
number, number -\u003e number
string, string -\u003e string
… << …
… >> …
… >>> …
Shift Beats Left
Shift bits right with sign preservation
Shift bits right with zero padding
from left to right
from left to right
from left to right
2
2
2
whole, whole → whole
whole, whole → whole
whole, whole → whole
… < …
… <= …
… > …
… >= …
... in ...
... instanceof ...
Less than
Less or equal
More than
More or equal
Checking for the existence of a property
Checking for belonging to this type
from left to right
from left to right
from left to right
from left to right
from left to right
from left to right
2
2
2
2
2
2
number, number -\u003e boolean
number, number -\u003e boolean
number, number -\u003e boolean
number, number -\u003e boolean
string, object -\u003e boolean
object, constructor -\u003e boolean
… == …
… != …
… === …
… !== …
Equally
Not equal
Strictly equal
Strictly not equal
from left to right
from left to right
from left to right
from left to right
2
2
2
2
any, any -\u003e boolean
any, any -\u003e boolean
any, any -\u003e boolean
any, any -\u003e boolean
… & … Bitwise AND from left to right 2 whole, whole → whole
… ^ … Bitwise EXCLUSIVE OR from left to right 2 whole, whole → whole
… | … Assignment operation
Assignment operation
Assignment operation
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
from right to left
2
2
2
2
2
2
2
2
2
2
2
2
2
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
lval, any -\u003e any
yield ...
yield * ...
yield
yield *
from right to left
from right to left
1
1
... … Expansion is absent 1
… , … Comma from left to right 2 any, any → any