JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript operators.

Javascript operators are used to perform different types of mathematical and logical computations.

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

JavaScript Assignment

The Assignment Operator ( = ) assigns a value to a variable:

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator ( += ) adds a value to a variable.

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

Note that strings are compared alphabetically:

JavaScript String Addition

The + can also be used to add (concatenate) strings:

The += assignment operator can also be used to add (concatenate) strings:

The result of text1 will be:

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

The result of x , y , and z will be:

If you add a number and a string, the result will be a string!

JavaScript Logical Operators

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers. Because of this, in JavaScript, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Basic operators, maths

We know many operators from school. They are things like addition + , multiplication * , subtraction - , and so on.

In this chapter, we’ll start with simple operators, then concentrate on JavaScript-specific aspects, not covered by school arithmetic.

Terms: “unary”, “binary”, “operand”

Before we move on, let’s grasp some common terminology.

An operand – is what operators are applied to. For instance, in the multiplication of 5 * 2 there are two operands: the left operand is 5 and the right operand is 2 . Sometimes, people call these “arguments” instead of “operands”.

An operator is unary if it has a single operand. For example, the unary negation - reverses the sign of a number:

An operator is binary if it has two operands. The same minus exists in binary form as well:

Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction operator, a binary operator that subtracts one number from another.

The following math operations are supported:

  • Addition + ,
  • Subtraction - ,
  • Multiplication * ,
  • Division / ,
  • Remainder % ,
  • Exponentiation ** .

The first four are straightforward, while % and ** need a few words about them.

Remainder %

The remainder operator % , despite its appearance, is not related to percents.

The result of a % b is the remainder of the integer division of a by b .

For instance:

Exponentiation **

The exponentiation operator a ** b raises a to the power of b .

In school maths, we write that as a b .

Just like in maths, the exponentiation operator is defined for non-integer numbers as well.

For example, a square root is an exponentiation by ½:

String concatenation with binary +

Let’s meet the features of JavaScript operators that are beyond school arithmetics.

Usually, the plus operator + sums numbers.

But, if the binary + is applied to strings, it merges (concatenates) them:

Note that if any of the operands is a string, then the other one is converted to a string too.

For example:

See, it doesn’t matter whether the first operand is a string or the second one.

Here’s a more complex example:

Here, operators work one after another. The first + sums two numbers, so it returns 4 , then the next + adds the string 1 to it, so it’s like 4 + '1' = '41' .

Here, the first operand is a string, the compiler treats the other two operands as strings too. The 2 gets concatenated to '1' , so it’s like '1' + 2 = "12" and "12" + 2 = "122" .

The binary + is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.

Here’s the demo for subtraction and division:

Numeric conversion, unary +

The plus + exists in two forms: the binary form that we used above and the unary form.

The unary plus or, in other words, the plus operator + applied to a single value, doesn’t do anything to numbers. But if the operand is not a number, the unary plus converts it into a number.

It actually does the same thing as Number(...) , but is shorter.

The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?

The binary plus would add them as strings:

If we want to treat them as numbers, we need to convert and then sum them:

From a mathematician’s standpoint, the abundance of pluses may seem strange. But from a programmer’s standpoint, there’s nothing special: unary pluses are applied first, they convert strings to numbers, and then the binary plus sums them up.

Why are unary pluses applied to values before the binary ones? As we’re going to see, that’s because of their higher precedence .

Operator precedence

If an expression has more than one operator, the execution order is defined by their precedence , or, in other words, the default priority order of operators.

From school, we all know that the multiplication in the expression 1 + 2 * 2 should be calculated before the addition. That’s exactly the precedence thing. The multiplication is said to have a higher precedence than the addition.

Parentheses override any precedence, so if we’re not satisfied with the default order, we can use them to change it. For example, write (1 + 2) * 2 .

There are many operators in JavaScript. Every operator has a corresponding precedence number. The one with the larger number executes first. If the precedence is the same, the execution order is from left to right.

Here’s an extract from the precedence table (you don’t need to remember this, but note that unary operators are higher than corresponding binary ones):

As we can see, the “unary plus” has a priority of 14 which is higher than the 11 of “addition” (binary plus). That’s why, in the expression "+apples + +oranges" , unary pluses work before the addition.

Let’s note that an assignment = is also an operator. It is listed in the precedence table with the very low priority of 2 .

That’s why, when we assign a variable, like x = 2 * 2 + 1 , the calculations are done first and then the = is evaluated, storing the result in x .

Assignment = returns a value

The fact of = being an operator, not a “magical” language construct has an interesting implication.

All operators in JavaScript return a value. That’s obvious for + and - , but also true for = .

The call x = value writes the value into x and then returns it .

Here’s a demo that uses an assignment as part of a more complex expression:

In the example above, the result of expression (a = b + 1) is the value which was assigned to a (that is 3 ). It is then used for further evaluations.

Funny code, isn’t it? We should understand how it works, because sometimes we see it in JavaScript libraries.

Although, please don’t write the code like that. Such tricks definitely don’t make code clearer or readable.

Chaining assignments

Another interesting feature is the ability to chain assignments:

Chained assignments evaluate from right to left. First, the rightmost expression 2 + 2 is evaluated and then assigned to the variables on the left: c , b and a . At the end, all the variables share a single value.

Once again, for the purposes of readability it’s better to split such code into few lines:

That’s easier to read, especially when eye-scanning the code fast.

Modify-in-place

We often need to apply an operator to a variable and store the new result in that same variable.

This notation can be shortened using the operators += and *= :

Short “modify-and-assign” operators exist for all arithmetical and bitwise operators: /= , -= , etc.

Such operators have the same precedence as a normal assignment, so they run after most other calculations:

Increment/decrement

Increasing or decreasing a number by one is among the most common numerical operations.

So, there are special operators for it:

Increment ++ increases a variable by 1:

Decrement -- decreases a variable by 1:

Increment/decrement can only be applied to variables. Trying to use it on a value like 5++ will give an error.

The operators ++ and -- can be placed either before or after a variable.

  • When the operator goes after the variable, it is in “postfix form”: counter++ .
  • The “prefix form” is when the operator goes before the variable: ++counter .

Both of these statements do the same thing: increase counter by 1 .

Is there any difference? Yes, but we can only see it if we use the returned value of ++/-- .

Let’s clarify. As we know, all operators return a value. Increment/decrement is no exception. The prefix form returns the new value while the postfix form returns the old value (prior to increment/decrement).

To see the difference, here’s an example:

In the line (*) , the prefix form ++counter increments counter and returns the new value, 2 . So, the alert shows 2 .

Now, let’s use the postfix form:

In the line (*) , the postfix form counter++ also increments counter but returns the old value (prior to increment). So, the alert shows 1 .

To summarize:

If the result of increment/decrement is not used, there is no difference in which form to use:

If we’d like to increase a value and immediately use the result of the operator, we need the prefix form:

If we’d like to increment a value but use its previous value, we need the postfix form:

The operators ++/-- can be used inside expressions as well. Their precedence is higher than most other arithmetical operations.

Compare with:

Though technically okay, such notation usually makes code less readable. One line does multiple things – not good.

While reading code, a fast “vertical” eye-scan can easily miss something like counter++ and it won’t be obvious that the variable increased.

We advise a style of “one line – one action”:

Bitwise operators

Bitwise operators treat arguments as 32-bit integer numbers and work on the level of their binary representation.

These operators are not JavaScript-specific. They are supported in most programming languages.

The list of operators:

  • AND ( & )
  • LEFT SHIFT ( << )
  • RIGHT SHIFT ( >> )
  • ZERO-FILL RIGHT SHIFT ( >>> )

These operators are used very rarely, when we need to fiddle with numbers on the very lowest (bitwise) level. We won’t need these operators any time soon, as web development has little use of them, but in some special areas, such as cryptography, they are useful. You can read the Bitwise Operators chapter on MDN when a need arises.

The comma operator , is one of the rarest and most unusual operators. Sometimes, it’s used to write shorter code, so we need to know it in order to understand what’s going on.

The comma operator allows us to evaluate several expressions, dividing them with a comma , . Each of them is evaluated but only the result of the last one is returned.

Here, the first expression 1 + 2 is evaluated and its result is thrown away. Then, 3 + 4 is evaluated and returned as the result.

Please note that the comma operator has very low precedence, lower than = , so parentheses are important in the example above.

Without them: a = 1 + 2, 3 + 4 evaluates + first, summing the numbers into a = 3, 7 , then the assignment operator = assigns a = 3 , and the rest is ignored. It’s like (a = 1 + 2), 3 + 4 .

Why do we need an operator that throws away everything except the last expression?

Sometimes, people use it in more complex constructs to put several actions in one line.

Such tricks are used in many JavaScript frameworks. That’s why we’re mentioning them. But usually they don’t improve code readability so we should think well before using them.

The postfix and prefix forms

What are the final values of all variables a , b , c and d after the code below?

The answer is:

Assignment result

What are the values of a and x after the code below?

  • a = 4 (multiplied by 2)
  • x = 5 (calculated as 1 + 4)

Type conversions

What are results of these expressions?

Think well, write down and then compare with the answer.

  • The addition with a string "" + 1 converts 1 to a string: "" + 1 = "1" , and then we have "1" + 0 , the same rule is applied.
  • The subtraction - (like most math operations) only works with numbers, it converts an empty string "" to 0 .
  • The addition with a string appends the number 5 to the string.
  • The subtraction always converts to numbers, so it makes " -9 " a number -9 (ignoring spaces around it).
  • null becomes 0 after the numeric conversion.
  • undefined becomes NaN after the numeric conversion.
  • Space characters are trimmed off string start and end when a string is converted to a number. Here the whole string consists of space characters, such as \t , \n and a “regular” space between them. So, similarly to an empty string, it becomes 0 .

Fix the addition

Here’s a code that asks the user for two numbers and shows their sum.

It works incorrectly. The output in the example below is 12 (for default prompt values).

Why? Fix it. The result should be 3 .

The reason is that prompt returns user input as a string.

So variables have values "1" and "2" respectively.

What we should do is to convert strings to numbers before + . For example, using Number() or prepending them with + .

For example, right before prompt :

Or in the alert :

Using both unary and binary + in the latest code. Looks funny, doesn’t it?

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 29038

  • Patrick McClanahan
  • San Joaquin Delta College

Assignment Operator

The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol. But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value.

The value 21 is moved to the memory location for the variable named: age. Another way to say it: age is assigned the value 21.

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would assigned to the variable named: total_cousins.

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

As we have seen, assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:

  • “=” : This is the simplest assignment operator, which was discussed above. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';

If initially the value 5 is stored in the variable a,  then:  (a += 6) is equal to 11.  (the same as: a = a + 6)

If initially value 8 is stored in the variable a, then (a -= 6) is equal to  2. (the same as a = a - 6)

If initially value 5 is stored in the variable a,, then (a *= 6) is equal to 30. (the same as a = a * 6)

If initially value 6 is stored in the variable a, then (a /= 2) is equal to 3. (the same as a = a / 2)

Below example illustrates the various Assignment Operators:

Definitions

 Adapted from:  "Assignment Operator"  by  Kenneth Leroy Busbee , (Download for free at http://cnx.org/contents/[email protected] ) is licensed under  CC BY 4.0

Compound-Assignment Operators

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

Compound-Assignment Operators in Java

Java supports 11 compound-assignment operators:

Example Usage

To assign the result of an addition operation to a variable using the standard syntax:

But use a compound-assignment operator to effect the same outcome with the simpler syntax:

  • Conditional Operators
  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • The 7 Best Programming Languages to Learn for Beginners
  • Math Glossary: Mathematics Terms and Definitions
  • The Associative and Commutative Properties
  • The JavaScript Ternary Operator as a Shortcut for If/Else Statements
  • Parentheses, Braces, and Brackets in Math
  • Basic Guide to Creating Arrays in Ruby
  • Dividing Monomials in Basic Algebra
  • C++ Handling Ints and Floats
  • An Abbreviated JavaScript If Statement
  • Using the Switch Statement for Multiple Choices in Java
  • How to Make Deep Copies in Ruby
  • Definition of Variable
  • The History of Algebra

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Mathematics LibreTexts

2.4: Expressions and Operator Precedence

  • Last updated
  • Save as PDF
  • Page ID 53707

Expressions

An expression is a combination of variables, data elements (like numbers and strings), operations (like + or *) and functions (like ). We’ve seen a number of expressions throughout this chapter so far like

In short, writing things in julia will consist of writing expressions (and slightly more complicated structures).

Operator Precedence

When we type out an expression like 11+2*(4+3)^3 , it is important to understand the order in which operators are performed. For mathematics, the PEMDAS pnemonic is helpful to rememember in that the order is:

Parentheses : The expression inside the ( ) are done first. For the example above, the  4+3  is the first operation done.

Exponentials : The ^ is done next. Raise the 7 from above to the power of 3 resulting in 343 .

Multiplication and Division : In this example, the  2*(343)  is done next

Addition and Subtraction : Lastly add 11 to the result and the result is 697 .

In any computing language, there are other operators as well and there is order to that precedence, so we will see that there are other things to think about. For example, the assignment operator, has the lowest precedence. That is when assigning something to a variable, all calculations are done on the right side of the = before the assignment.

Details on all this can be found on the JULIA DOCUMENTATION ON OPERATOR PRECEDENCE

A comment in computer code is sequences of characters which are ignored. The purpose of a comment is to alert a human on what is going on. You may have been told to write comments so that someone else who reads your code understands what you are doing. However, I have found that the person mostly like to read your code is you at a later date. You should add comments for yourself.

In julia, a comment is anything to the right of a , pound sign or hash tag. For example:

Both lines 1 and 3 have comments. On line 1, the entire line is ignore since the line starts with # . On line 3, everything after the 2 (the power) is ignored. Also, notice that there are two hash tags on line 1 and 1 on line 3. This is simply different style. Since anything after a single is a comment, everything after the first one is ignored.

CS105: Introduction to Python

math assignment operator

Practice With Arithmetic Operators

Practice these programming examples to internalize these concepts.

9. Assignment Operators

The most common assignment operator is one you have already used: the equals sign  = . The  =  assignment operator assigns the value on the right to a variable on the left. For example,  v = 23  assigns the value of the integer  23  to the variable  v .

When programming, it is common to use compound assignment operators that perform an operation on a variable’s value and then assign the resulting new value to that variable. These compound operators combine an arithmetic operator with the  =  operator, so for addition we’ll combine  +  with  =  to get the compound operator  += . Let’s see what that looks like:

First, we set the variable  w  equal to the value of  5 , then we used the  +=  compound assignment operator to add the right number to the value of the left variable  and then  assign the result to  w .

Compound assignment operators are used frequently in the case of for loops, which you’ll use when you want to repeat a process several times:

With the for loop, we were able to automate the process of the  *=  operator that multiplied the variable  w  by the number  2  and then assigned the result in the variable  w  for the next iteration of the for loop.

Python has a compound assignment operator for each of the arithmetic operators discussed in this tutorial:

Compound assignment operators can be useful when things need to be incrementally increased or decreased, or when you need to automate certain processes in your program.

Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise

Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.

Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.

Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.

Python includes the following categories of operators:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.

Arithmetic operators perform the common mathematical operation on the numeric operands.

The arithmetic operators return the type of result depends on the type of operands, as below.

  • If either operand is a complex number, the result is converted to complex;
  • If either operand is a floating point number, the result is converted to floating point;
  • If both operands are integers, then the result is an integer and no conversion is needed.

The following table lists all the arithmetic operators in Python:

The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:

The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.

The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.

The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.

The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .

Bitwise operators perform operations on binary operands.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

math assignment operator

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Assignment Operators in Python

  • Augmented Assignment Operators in Python
  • Python Arithmetic Operators
  • Division Operators in Python
  • Python Bitwise Operators
  • Chaining comparison operators in Python
  • Increment and Decrement Operators in Python
  • Python Operators
  • Python: Operations on Numpy Arrays
  • Python Membership and Identity Operators
  • Modulo operator (%) in Python
  • Python NOT EQUAL operator
  • Assignment Operators in C
  • Assignment Operators In C++
  • Assignment Operators in Programming
  • Solidity - Assignment Operators
  • C++ Assignment Operator Overloading
  • JavaScript Assignment Operators
  • Java Assignment Operators with Examples
  • Compound assignment operators in Java
  • Adding new column to existing DataFrame in Pandas
  • Python map() function
  • Read JSON file using Python
  • How to get column names in Pandas dataframe
  • Taking input in Python
  • Read a file line by line in Python
  • Dictionaries in Python
  • Enumerate() in Python
  • Iterate over a list in Python
  • Different ways to create Pandas Dataframe

Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, bitwise computations. The value the operator operates on is known as Operand .

Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables. 

Now Let’s see each Assignment Operator one by one.

1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand.

2) Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to the left operand.

Syntax: 

3) Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to the left operand.

Example –

 4) Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to the left operand.

 5) Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the left operand.

 6) Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the result to the left operand.

7) Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the result(floor) to the left operand.

 8) Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

9) Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the left operand.

10) Bitwise OR and Assign: This operator is used to perform Bitwise OR on the operands and then assigning result to the left operand.

11) Bitwise XOR and Assign:  This operator is used to perform Bitwise XOR on the operands and then assigning result to the left operand.

12) Bitwise Right Shift and Assign: This operator is used to perform Bitwise right shift on the operands and then assigning result to the left operand.

 13) Bitwise Left Shift and Assign:  This operator is used to perform Bitwise left shift on the operands and then assigning result to the left operand.

Please Login to comment...

Similar reads.

author

  • Python-Operators

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. Difference between $:=$ and

    3. The equality symbol = denotes an operator that is part of the object theory. The definition symbol ≜ ≜ (and its variants) denotes a syntactic replacement, and is part of the metatheory. This distinction is emphasized in the formal syntax of TLA+, whose axioms are those of Zermelo-Fraenkel set theory + Hilbert's ε ε, and functions.

  2. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

  3. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  4. Addition assignment (+=)

    The addition assignment (+=) operator performs addition (which is either numeric addition or string concatenation) on the two operands and assigns the result to the left operand.

  5. JavaScript Operators

    Javascript operators are used to perform different types of mathematical and logical computations. Examples: The Assignment Operator = assigns values. The Addition Operator + adds values. The Multiplication Operator * multiplies values. The Comparison Operator > compares values

  6. Basic math in JavaScript

    Operator Name Purpose Example Shortcut for += Addition assignment: Adds the value on the right to the variable value on the left, then returns the new variable value x += 4; x = x + 4;-= Subtraction assignment: Subtracts the value on the right from the variable value on the left, and returns the new variable value x -= 3; x = x - 3; *=

  7. Assignment operators

    An assignment operator assigns a value to its left operand based on the value of its right operand.. Overview. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = y assigns the value of y to x.The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples.

  8. Expressions and operators

    The shorthand assignment operator += can also be used to concatenate strings. For example, var mystring = 'alpha'; mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring. Conditional (ternary) operator. The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two ...

  9. Basic operators, maths

    An operator is binary if it has two operands. The same minus exists in binary form as well: let x = 1, y = 3; alert( y - x ); // 2, binary minus subtracts values. Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction ...

  10. How To Do Math in JavaScript with Operators

    In addition to the standard assignment operator, JavaScript has compound assignment operators, which combine an arithmetic operator with =. For example, the addition operator will start with the original value, and add a new value. // Assign 27 to age variable let age = 27; age += 3; console.log(age); Output.

  11. operators

    In computer programming languages, the equals sign typically denotes either a boolean operator to test equality of values (e.g. as in Pascal or Eiffel), which is consistent with the symbol's usage in mathematics, or an assignment operator (e.g. as in C-like languages). Languages making the former choice often use a colon-equals (:=) or ≔ to ...

  12. 4.6: Assignment Operator

    Assignment Operator. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol.

  13. What Are Assignment Operators

    Basic Assignment Operator. The most common assignment operator is the simple equals sign (=), which assigns the value on its right to the variable on its left. Here's a straightforward example: let x = 5; console.log(x); // Outputs: 5. This operator is used to initialize variables, and it can also be used to reassign new values to existing variables:

  14. What Is a Compound-Assignment Operator?

    Compound-Assignment Operators. Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

  15. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  16. JavaScript Assignment Operators

    Addition Assignment Operator(+=) The Addition assignment operator adds the value to the right operand to a variable and assigns the result to the variable. Addition or concatenation is possible. In case of concatenation then we use the string as an operand.

  17. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.

  18. 2.4: Expressions and Operator Precedence

    Operator Precedence. When we type out an expression like 11+2*(4+3)^3, it is important to understand the order in which operators are performed. For mathematics, the PEMDAS pnemonic is helpful to rememember in that the order is: Parentheses: The expression inside the ( ) are done first. For the example above, the 4+3 is the first operation done ...

  19. Practice With Arithmetic Operators: Assignment Operators

    The most common assignment operator is one you have already used: the equals sign =.The = assignment operator assigns the value on the right to a variable on the left.For example, v = 23 assigns the value of the integer 23 to the variable v. When programming, it is common to use compound assignment operators that perform an operation on a variable's value and then assign the resulting new ...

  20. Mathematical operators and symbols in Unicode

    The Unicode Standard encodes almost all standard characters used in mathematics. Unicode Technical Report #25 provides comprehensive information about the character repertoire, their properties, and guidelines for implementation. Mathematical operators and symbols are in multiple Unicode blocks.Some of these blocks are dedicated to, or primarily contain, mathematical characters while others ...

  21. Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity

    Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...

  22. Assignment Operators in Python

    1) Assign: This operator is used to assign the value of the right side of the expression to the left side operand. Syntax: x = y + z. Example: Python3. # Assigning values using . # Assignment Operator. a = 3. b = 5.

  23. Mathematical Assignment Operators

    Mathematical Assignment Operators. One common task when manipulating number variables is to reassign them to their old value with some operation performed on it. This is such a common task that PHP provides a shorter syntax using arithmetic assignment operators: We could use this shorter syntax to rewrite the above code: With mathematical ...