operator-assignment

Require or disallow assignment operator shorthand where possible

Some problems reported by this rule are automatically fixable by the --fix command line option

JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, x = x + 4 can be shortened to x += 4 . The supported shorthand forms are as follows:

Rule Details

This rule requires or disallows assignment operator shorthand where possible.

The rule applies to the operators listed in the above table. It does not report the logical assignment operators &&= , ||= , and ??= because their short-circuiting behavior is different from the other assignment operators.

This rule has a single string option:

  • "always" (default) requires assignment operator shorthand where possible
  • "never" disallows assignment operator shorthand

Examples of incorrect code for this rule with the default "always" option:

Examples of correct code for this rule with the default "always" option:

Examples of incorrect code for this rule with the "never" option:

Examples of correct code for this rule with the "never" option:

When Not To Use It

Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis.

This rule was introduced in ESLint v0.10.0.

  • Rule source
  • Tests source

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

Operator precedence

Operator overloading

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update: operator-assignment should indicate which operator can be shortened #14764

Conversation.

paulsmithkc

paulsmithkc commented Jul 2, 2021 • edited

Prerequisites checklist.

  • I have read the contributing guidelines .

What is the purpose of this pull request? (put an "X" next to an item)

[ ] Documentation update [ ] Bug fix ( template ) [ ] New rule ( template ) [x] Changes an existing rule ( template ) [ ] Add autofixing to a rule [ ] Add a CLI option [ ] Add something to the core [ ] Other, please explain:

What rule do you want to change?

operator-assignment

Does this change cause the rule to produce more or fewer warnings?

How will the change be implemented? (New option, new default behavior, etc.)?

new default behavior

Please provide some example code that this change will affect:

What does the rule currently do for this code?

Current error message: "Assignment can be replaced with operator assignment."

What will the rule do after it's changed?

New error message: "Assignment (=) can be replaced with operator assignment (+=)."

What changes did you make? (Give an overview)

  • Introduced an "operator" token that can be used in the error message.
  • Updated the error messages to use this token.

Is there anything you'd like reviewers to focus on?

Are there any other ways to make this error message less cryptic?

Sorry, something went wrong.

@paulsmithkc

nzakas left a comment

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more .

LGTM. Thanks.

@nzakas

snitin315 left a comment

LGTM, thanks!

btmills

btmills left a comment

This is a nice improvement!

  • 👍 1 reaction

@btmills

Successfully merging this pull request may close these issues.

@paulsmithkc

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators

  • 8 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator keywords.

Three of the compound assignment operators have keyword equivalents. They are:

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

The built-in e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type, or it must be a constant expression that evaluates to 0. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of built-in assignment operators

The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Assignment operators

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

Simple assignment

The simple assignment operator expressions have the form

Assignment performs implicit conversion from the value of rhs to the type of rhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict -qualified or atomic .
  • lhs is a pointer (possibly qualified or atomic) and rhs is a null pointer constant such as NULL
  • lhs has type _Bool (possibly qualified or atomic) and rhs is a pointer

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C

Compound assignment

The compound assignment operator expressions have the form

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

Operator precedence

Inspectopedia Help

Assignment can be replaced with operator assignment.

Reports assignment operations which can be replaced by operator-assignment.

Code using operator assignment is shorter and may be clearer.

After the quick fix is applied:

Use the Ignore conditional operators option to ignore && and || . Replacing conditional operators with operator assignment would change the evaluation from lazy to eager, which may change the semantics of the expression.

Use the Ignore obscure operators option to ignore ^ and % , which are less known.

Inspection options

Here you can find the description of settings available for the Assignment can be replaced with operator assignment inspection, and the reference of their default values.

Default: Selected

Not selected

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 203 – Augmented Assignments

Introduction, proposed semantics, new methods, implementation, open issues.

This PEP describes the augmented assignment proposal for Python 2.0. This PEP tracks the status and ownership of this feature, slated for introduction in Python 2.0. It contains a description of the feature and outlines changes necessary to support the feature. This PEP summarizes discussions held in mailing list forums [1] , and provides URLs for further information where appropriate. The CVS revision history of this file contains the definitive historical record.

The proposed patch that adds augmented assignment to Python introduces the following new operators:

They implement the same operator as their normal binary form, except that the operation is done in-place when the left-hand side object supports it, and that the left-hand side is only evaluated once.

They truly behave as augmented assignment, in that they perform all of the normal load and store operations, in addition to the binary operation they are intended to do. So, given the expression:

The object x is loaded, then y is added to it, and the resulting object is stored back in the original place. The precise action performed on the two arguments depends on the type of x , and possibly of y .

The idea behind augmented assignment in Python is that it isn’t just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left-hand operand in question to know that it should operate on itself , rather than creating a modified copy of itself.

To make this possible, a number of new hooks are added to Python classes and C extension types, which are called when the object in question is used as the left hand side of an augmented assignment operation. If the class or type does not implement the in-place hooks, the normal hooks for the particular binary operation are used.

So, given an instance object x , the expression:

tries to call x.__iadd__(y) , which is the in-place variant of __add__ . If __iadd__ is not present, x.__add__(y) is attempted, and finally y.__radd__(x) if __add__ is missing too. There is no right-hand-side variant of __iadd__ , because that would require for y to know how to in-place modify x , which is unsafe to say the least. The __iadd__ hook should behave similar to __add__ , returning the result of the operation (which could be self ) which is to be assigned to the variable x .

For C extension types, the hooks are members of the PyNumberMethods and PySequenceMethods structures. Some special semantics apply to make the use of these methods, and the mixing of Python instance objects and C types, as unsurprising as possible.

In the generic case of x <augop> y (or a similar case using the PyNumber_InPlace API functions) the principal object being operated on is x . This differs from normal binary operations, where x and y could be considered co-operating , because unlike in binary operations, the operands in an in-place operation cannot be swapped. However, in-place operations do fall back to normal binary operations when in-place modification is not supported, resulting in the following rules:

If coercion does not yield a different object for x , or x does not define a __coerce__ method, and x has the appropriate __ihook__ for this operation, call that method with y as the argument, and the result of the operation is whatever that method returns.

Note that no coercion on either x or y is done in this case, and it’s perfectly valid for a C type to receive an instance object as the second argument; that is something that cannot happen with normal binary operations.

  • Otherwise, process it exactly as a normal binary operation (not in-place), including argument coercion. In short, if either argument is an instance object, resolve the operation through __coerce__ , __hook__ and __rhook__ . Otherwise, both objects are C types, and they are coerced and passed to the appropriate function.
  • If no way to process the operation can be found, raise a TypeError with an error message specific to the operation.
  • Some special casing exists to account for the case of + and * , which have a special meaning for sequences: for + , sequence concatenation, no coercion what so ever is done if a C type defines sq_concat or sq_inplace_concat . For * , sequence repeating, y is converted to a C integer before calling either sq_inplace_repeat and sq_repeat . This is done even if y is an instance, though not if x is an instance.

The in-place function should always return a new reference, either to the old x object if the operation was indeed performed in-place, or to a new object.

There are two main reasons for adding this feature to Python: simplicity of expression, and support for in-place operations. The end result is a tradeoff between simplicity of syntax and simplicity of expression; like most new features, augmented assignment doesn’t add anything that was previously impossible. It merely makes these things easier to do.

Adding augmented assignment will make Python’s syntax more complex. Instead of a single assignment operation, there are now twelve assignment operations, eleven of which also perform a binary operation. However, these eleven new forms of assignment are easy to understand as the coupling between assignment and the binary operation, and they require no large conceptual leap to understand. Furthermore, languages that do have augmented assignment have shown that they are a popular, much used feature. Expressions of the form:

are common enough in those languages to make the extra syntax worthwhile, and Python does not have significantly fewer of those expressions. Quite the opposite, in fact, since in Python you can also concatenate lists with a binary operator, something that is done quite frequently. Writing the above expression as:

is both more readable and less error prone, because it is instantly obvious to the reader that it is <x> that is being changed, and not <x> that is being replaced by something almost, but not quite, entirely unlike <x> .

The new in-place operations are especially useful to matrix calculation and other applications that require large objects. In order to efficiently deal with the available program memory, such packages cannot blindly use the current binary operations. Because these operations always create a new object, adding a single item to an existing (large) object would result in copying the entire object (which may cause the application to run out of memory), add the single item, and then possibly delete the original object, depending on reference count.

To work around this problem, the packages currently have to use methods or functions to modify an object in-place, which is definitely less readable than an augmented assignment expression. Augmented assignment won’t solve all the problems for these packages, since some operations cannot be expressed in the limited set of binary operators to start with, but it is a start. PEP 211 is looking at adding new operators.

The proposed implementation adds the following 11 possible hooks which Python classes can implement to overload the augmented assignment operations:

The i in __iadd__ stands for in-place .

For C extension types, the following struct members are added.

To PyNumberMethods :

To PySequenceMethods :

In order to keep binary compatibility, the tp_flags TypeObject member is used to determine whether the TypeObject in question has allocated room for these slots. Until a clean break in binary compatibility is made (which may or may not happen before 2.0) code that wants to use one of the new struct members must first check that they are available with the PyType_HasFeature() macro:

This check must be made even before testing the method slots for NULL values! The macro only tests whether the slots are available, not whether they are filled with methods or not.

The current implementation of augmented assignment [2] adds, in addition to the methods and slots already covered, 13 new bytecodes and 13 new API functions.

The API functions are simply in-place versions of the current binary-operation API functions:

They call either the Python class hooks (if either of the objects is a Python class instance) or the C type’s number or sequence methods.

The new bytecodes are:

The INPLACE_* bytecodes mirror the BINARY_* bytecodes, except that they are implemented as calls to the InPlace API functions. The other two bytecodes are utility bytecodes: ROT_FOUR behaves like ROT_THREE except that the four topmost stack items are rotated.

DUP_TOPX is a bytecode that takes a single argument, which should be an integer between 1 and 5 (inclusive) which is the number of items to duplicate in one block. Given a stack like this (where the right side of the list is the top of the stack):

DUP_TOPX 3 would duplicate the top 3 items, resulting in this stack:

DUP_TOPX with an argument of 1 is the same as DUP_TOP . The limit of 5 is purely an implementation limit . The implementation of augmented assignment requires only DUP_TOPX with an argument of 2 and 3, and could do without this new opcode at the cost of a fair number of DUP_TOP and ROT_* .

The PyNumber_InPlace API is only a subset of the normal PyNumber API: only those functions that are required to support the augmented assignment syntax are included. If other in-place API functions are needed, they can be added later.

The DUP_TOPX bytecode is a conveniency bytecode, and is not actually necessary. It should be considered whether this bytecode is worth having. There seems to be no other possible use for this bytecode at this time.

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0203.rst

Last modified: 2023-09-09 17:39:29 GMT

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

  • Binary Operators in Programming
  • Operator Associativity in Programming
  • C++ Assignment Operator Overloading
  • What are Operators in Programming?
  • Assignment Operators In C++
  • Bitwise AND operator in Programming
  • Increment and Decrement Operators in Programming
  • Types of Operators in Programming
  • Logical AND operator in Programming
  • Modulus Operator in Programming
  • Solidity - Assignment Operators
  • Augmented Assignment Operators in Python
  • Pre Increment and Post Increment Operator in Programming
  • Right Shift Operator (>>) in Programming
  • JavaScript Assignment Operators
  • Move Assignment Operator in C++ 11
  • Assignment Operators in Python
  • Assignment Operators in C
  • Subtraction Assignment( -=) Operator in Javascript

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in C#
  • Assignment Operators in Javascript
  • Application of Assignment Operators

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 the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Select language
  • Skip to search
  • Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

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.

Simple assignment operator which assigns a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Exponentiation assignment

This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

Specifications

Browser compatibility.

  • Arithmetic operators

Document Tags and Contributors

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

COMMENTS

  1. Code Inspection: Assignment could be replaced with operator assignment

    Last modified: 11 February 2024. Configure inspections: Settings | Editor | Inspections. Show intention actions: Alt Enter. Reports an assignment operation that can be replaced by an operator assignment to make your code shorter and probably clearer. Example: x = x + 3; x = x / 3; After the quick fix is applied the result looks like:

  2. operator-assignment

    Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis. Version

  3. New rule: Assignment replaceable with operator assignment #1420

    This is the first rule from WebStorm Inspectors (rollup) #667. This inspection reports instances of assignment operations in JavaScript content which can be replaced by operator-assignment. Code using operator assignment may be clearer, and theoretically more performant. Valid patterns:

  4. Assignment operators

    For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment. Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b. Assignment operator syntax. The assignment expressions have the form

  5. Update: operator-assignment should indicate which operator can be

    operator-assignment. Does this change cause the rule to produce more or fewer warnings? no. How will the change be implemented? (New option, new default behavior, etc.)? new default behavior. Please provide some example code that this change will affect:

  6. Assignment operators

    Explanation. copy assignment operator replaces the contents of the object a with a copy of the contents of b (b is not modified). For class types, this is a special member function, described in copy assignment operator.. move assignment operator replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is a special ...

  7. Assignment operators

    The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.

  8. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of rhs and then replaces the value in the object designated by lhs with the converted value of rhs.. Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as (a = b) = c ...

  9. C++ overriding the assignment operator

    A operator=(const A &a) { std::cout<<"This is assignment operator."; return NULL; } You end up creating the return value of type A as per A(NULL), and as NULL is 0, that matches the A(int) constructor best, which is why you see: line 3 This is assignment operator.This is int cstr. value is 0.

  10. Assignment can be replaced with operator assignment

    Reports modifications of variables with a simple assignment (such as y = y + x) that can be replaced with an operator assignment. The quick-fix replaces the assignment with an assignment operator. Example: fun foo() { val list = mutableListOf(1, 2, 3) list = list + 4 } After the quick-fix is applied: ...

  11. Assignment can be replaced with operator assignment

    Reports assignment operations which can be replaced by operator-assignment. Code using operator assignment is shorter and may be clearer. Example: x = x + 3; x = x / 3; After the quick fix is applied: x += 3; x /= 3; Use the Ignore conditional operators option to ignore && and ||. Replacing conditional operators with operator assignment would ...

  12. PEP 203

    They implement the same operator as their normal binary form, except that the operation is done in-place when the left-hand side object supports it, and that the left-hand side is only evaluated once.. They truly behave as augmented assignment, in that they perform all of the normal load and store operations, in addition to the binary operation they are intended to do.

  13. Augmented Assignment Operators in Python

    It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable "a" and assign the result back to "a", then instead of writing normally as "a = a + 7", we can use the augmented assignment operator and write the expression as "a += 7". Here ...

  14. terminology

    The assignment statement is made up of three parts:. The target, or lvalue.; The assignment operator.; The value to be assigned, or rvalue.; The rvalue can be a constant or an expression that returns a value of the correct (or not necessarily correct, in some languages) type.

  15. 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 ...

  16. 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.

  17. The Assignment Operator in R: Does "<-" work all the time, in

    R has several assignment operators. Per the documentation. The operator <-can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.. The only place I am aware of where you must use the <-operator is naming items of a list in attach.

  18. What alternatives are there for C/C++ assignment operator (=) and

    That said, to mean assignment, the =, :=, <-and ← operators are common across many languages descending from C, Pascal and BASIC. Vale uses a set keyword to mean reassignment. In languages where the concept of "(re)assignment" does not exist, like most Functional and Logical ones, it is not uncommon to see = be used both for bindings and as ...