• Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Difference between For Loop and While Loop in Programming
  • Function Calling in Programming
  • Goto Statement in Programming
  • Function Declaration vs. Function Definition
  • Loops in Programming
  • What are Operators in Programming?
  • Write a Program to Print 2024 Calendar
  • Print Happy New Year 2024
  • Write a Program to Print Holiday Calendar 2024
  • Variables in Programming
  • Do While loop Syntax
  • Nested Loops in Programming
  • While loop Syntax
  • For loop Syntax
  • Bitwise OR Operator (|) in Programming
  • Functions in Programming
  • Unary Operators in Programming
  • Convert char to int (Characters to Integers)
  • Increment and Decrement Operators in Programming

Assignment Operators in Programming

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 C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • 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

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • C - Recursion
  • C - Scope Rules
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointer Arithmetics
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operand to the left of = symbol, which is defined as a simple assignment operator in C. In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple assignment operator (=)

The = operator is the most frequently used operator in C. As per ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented assignment operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression a+=b has the same effect of performing a+b first and then assigning the result back to the variable a.

Similarly, the expression a<<=b has the same effect of performing a<<b first and then assigning the result back to the variable a.

Here is a C program that demonstrates the use of assignment operators in C:

When you compile and execute the above program, it produces the following result −

  • Assignment Operators

Just like Arithmetic Operators, C++ has Assignment Operators. In order to give value to the variable in the program, an operator is needed. This function is provided by the Assignment Operators. Assignment Operators in programming languages are pre-defined operators which are used to assign values to the variables. Let us look at these Assignment operators in more detail.

assignment operators

  • Assignment Operators are used to assigning the results of an expression or constant to a variable.
  • In order to assign values to a variable, we use the Assignment Operator  in the programming language.

Assignment Operator is a type of Binary Operator wherein it needs two operands to function. The left side operand is the variable and the right side of the operand is the value to be assigned.

The symbol which is used by the Assignment Operator is ‘ = ’.

Copy Code Copied Use a different Browser

The assignment operator can be used within any valid expression. An expression can be a combination of variables, constants, and operators arranged as per the syntax and precedence levels of the programming language.

During the use of the assignment operator, always the right-hand side of the operator is computed first, and then it is assigned to the variable defined on the left-hand side of the statement.

Note:  The source (right-hand side) and destination (left-hand side) should always be of the same data type.

Browse all the Topics Under Operator and Expressions: Operators

  • Arithmetic Operators
  • C++ Shorthands
  • Unary Operator
  • Increment and Decrement Operators
  • Relation Operator
  • Logical Operators

Types of Assignment Operators

In C++, there are 2 categories of Assignment Operators

  • Simple Assignment Operator
  • Compound Assignment Operator

Simple Assignment Operator (=) :

This is the usual assignment operator. Simple-assignment operator assigns its right operand to its left operand. In easy terms, this operator is used to assign the value on the right to the variable on the left.

Compound Assignment Operator:

These type of Operators are also known as Short-hand assignment operators.

Its syntax is,

where OP is a binary operator and is known as short-hand assignment operator.

While first initializing the variable, we cannot use the Short-hand operators. This will give a declaration error at the compile time of the program. Let’s understand this by looking at an example –

Compile-time Error. Value of variable ‘a’ not defined.

In the above program, we can see that in the initialization statement, we did not assign the value of 10 to the variable ‘a’ but instead we used the shorthand assignment operator which means

But the value of ‘a’ has not been defined. The compiler does not know the value stored in the location of variable ‘a’. Hence a compile-time error occurs.

FAQs on Assignment Operators

Q1. Equality Operator is denoted by?

  • None of the above

Answer. Option C

Q2. Assignment Operator is an example of ______ operator.

  • Conditional

Answer. Option B

Q3. Which of the following is an invalid assignment operator?

  • None of the Above

Customize your course in 30 seconds

Which class are you in.

tutor

Operator and Expressions: Operators

  • Shorthand Operators
  • Unary Operators
  • Increment & Decrement Operators
  • Relational Operators

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Download the App

Google Play

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 assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

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.

Codeforwin

Assignment and shorthand assignment operator in C

Quick links.

  • Shorthand assignment

Assignment operator is used to assign value to a variable (memory location). There is a single assignment operator = in C. It evaluates expression on right side of = symbol and assigns evaluated value to left side the variable.

For example consider the below assignment table.

The RHS of assignment operator must be a constant, expression or variable. Whereas LHS must be a variable (valid memory location).

Shorthand assignment operator

C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator.

For example, consider following C statements.

The above expression a = a + 2 is equivalent to a += 2 .

Similarly, there are many shorthand assignment operators. Below is a list of shorthand assignment operators in C.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Expressions and operators

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

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

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

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

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 . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

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

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

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 following table:

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

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.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

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 a comparison operator but rather is 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: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • 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). ~x evaluates to the same value that -x - 1 evaluates to.

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 either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

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.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

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 ( , ) 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. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

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's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

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 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 to avoid precedence issues.

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, numeric, or symbol 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.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

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

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.

Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

Summary : in this tutorial, you will learn how to use JavaScript assignment operators to assign a value to a variable.

Introduction to JavaScript assignment operators

An assignment operator ( = ) assigns a value to a variable. The syntax of the assignment operator is as follows:

In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a .

The following example declares the counter variable and initializes its value to zero:

The following example increases the counter variable by one and assigns the result to the counter variable:

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the second assignment, the counter variable is 1 .

To make the code more concise, you can use the += operator like this:

In this syntax, you don’t have to repeat the counter variable twice in the assignment.

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

Chaining JavaScript assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.
  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

Java assignment operators are classified into two types: simple and compound .

The Simple assignment operator is the equals ( = ) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left.

Compound operators are comprised of both an arithmetic, bitwise, or shift operator in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * and = operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com

IMAGES

  1. Assignment Operators in Java with Examples

    what is assignment operators

  2. Python Operator

    what is assignment operators

  3. PPT

    what is assignment operators

  4. Python Tutorials: Assignment Operators In python

    what is assignment operators

  5. PPT

    what is assignment operators

  6. Assignment Operators in C

    what is assignment operators

VIDEO

  1. ASSIGNMENT OPERATORS

  2. Assignment Operators in Typescript

  3. U 1 Assignment Operators, Relational Operators,Increment and Decrement Operators

  4. 014(Assignment Operators)JavaScript

  5. Javascript Session-5:Expression and Operators

  6. 06_Ruby basics ( Assignment Operators)

COMMENTS

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

  2. What is Assignment Operator?

    Assignment Operator: An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands. Unlike in C++, assignment ...

  3. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  4. C++ Assignment Operators

    Assignment Operators. Assignment operators are used to assign values to variables. In the example below, we use the assignment operator ( =) to assign the value 10 to a variable called x:

  5. Assignment Operators in C

    Assignment Operators in C - In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operan

  6. C Assignment Operators

    The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: | =. In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place.

  7. Assignment operators

    The assignment operator = is right-associative, that is, an expression of the form. a = b = c is evaluated as. a = (b = c) The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:

  8. Assignment Operators in C++

    Assignment Operators are used to assigning the results of an expression or constant to a variable. In order to assign values to a variable, we use the Assignment Operator in the programming language. Assignment Operators. Assignment Operator is a type of Binary Operator wherein it needs two operands to function.

  9. JavaScript Assignment

    The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable. Bitwise AND Assignment Example. let x = 10; x &= 5;

  10. Python's Assignment Operator: Write Robust Assignments

    The central component of an assignment statement is the assignment operator. This operator is represented by the = symbol, which separates two operands: A variable ; A value or an expression that evaluates to a concrete value; Operators are special symbols that perform mathematical, logical, and bitwise operations in a programming language.

  11. Assignment and shorthand assignment operator in C

    Assignment operator is used to assign value to a variable (memory location). There is a single assignment operator = in C. It evaluates expression on right side of = symbol and assigns evaluated value to left side the variable.. For example consider the below assignment table.

  12. Expressions and operators

    Expressions and operators. This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value.

  13. JavaScript Assignment Operators

    An assignment operator ( =) assigns a value to a variable. The syntax of the assignment operator is as follows: let a = b; Code language: JavaScript (javascript) In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a. The following example declares the counter variable and initializes its value to zero:

  14. Java Assignment Operators

    Java assignment operators are classified into two types: simple and compound. The Simple assignment operator is the equals ( =) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...

  15. c++

    An assignment operator is used to replace the data of a previously initialized object with some other object's data. A& operator=(const A& rhs) {data_ = rhs.data_; return *this;} For example: A aa; A a; a = aa; // assignment operator You could replace copy construction by default construction plus assignment, but that would be less efficient.

  16. Assignment Operators

    The following are the assignment operators defined in Visual Basic. = Operator ^= Operator *= Operator /= Operator \= Operator += Operator-= Operator <<= Operator >>= Operator &= Operator. See also. Operator Precedence in Visual Basic; Operators Listed by Functionality; Statements

  17. Assignment, Arithmetic, and Unary Operators

    The Simple Assignment Operator. One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left: int cadence = 0; int speed = 0; int gear = 1;

  18. What are the differences between "=" and "<-" assignment operators?

    The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example: median(x = 1:10) x. ## Error: object 'x' not found. In this case, x is declared within the scope of the function, so it does not exist in the user workspace. median(x <- 1:10)

  19. c++

    TestClass& operator=(const TestClass& Other); (you don't want to invoke the copy constructor for assignment, too) and it returns a reference to *this. A naive implementation would assign each data member individually: TestClass& operator=(const TestClass& Other) {. ClassName = Other.ClassName; return *this;