- This Website
- Chapter 1: Introduction
- Additional Problems
- Additional Examples
- Additional Notes
- Book (2nd ed.)
- Chapter 4: The core Python language II

## Assignment vs. the comparison operator

A common syntax error experienced by beginner Python programmers is in using the assignment operator = instead of the equality operator == in a conditional expression:

This assignment a = 5 does not return a value, it simply assigns the integer object 5 to the variable name a , and so there is nothing corresponding to True or False that the if statement can use: hence the SyntaxError . This contrasts with the C language in which an assignment returns the value of the variable being assigned (and so the statement a = 5 evaluates to true ). This behaviour is the source of many hard-to-find bugs and security vulnerabilities and its omission from the Python language is by design.

- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- Português (do Brasil)

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

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

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

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

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

Python includes the following categories of operators:

## Arithmetic Operators

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

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

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

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

The following table lists all the arithmetic operators in Python:

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

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

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

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

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

Bitwise operators perform operations on binary operands.

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

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

- Python Questions & Answers
- Python Skill Test
- Python Latest Articles

## Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators

## Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

## Python Assignment Operators

Assignment operators are used to assign values to variables:

Advertisement

## Python Comparison Operators

Comparison operators are used to compare two values:

## Python Logical Operators

Logical operators are used to combine conditional statements:

## Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

## Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

## Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

## Operator Precedence

Operator precedence describes the order in which operations are performed.

Parentheses has the highest precedence, meaning that expressions inside parentheses must be evaluated first:

Multiplication * has higher precedence than addition + , and therefor multiplications are evaluated before additions:

The precedence order is described in the table below, starting with the highest precedence at the top:

If two operators have the same precedence, the expression is evaluated from left to right.

Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from left to right:

## Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

## COLOR PICKER

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

## Introduction to Data Science I & II

Comparison operators, comparison operators #.

Comparison operators are used to compare values using mathematical logic and return a single Boolean value of either True or False . We will see later that they are important for counting, extracting and modifying data. For example, counting the number of students with GPA higher than a given threshold requires a comparison, for each student, of their GPA to the threshold.

In the cell below, Python compares two integers (is 5 strictly smaller than 7?) and returns the Boolean that reflects the comparison.

In the expression above, Python followed mathematical logic and declared the comparison to be true.

Below is a table of comparison operators.

To better understand how these operators work, we illustrate their use in the cell below where we compare two real numbers.

We showed examples of comparisons of integers and floats, but strings can also be used with comparison operators.

As you can see, Python compared the two strings and found them different, but is also able to use inequality operators to compare them. The order is determined lexicographically using the ASCII values of the characters.

Letter case is important for comparisons:

## Logical (boolean) operators #

Python’s logical operators perform Boolean arithmetic on one or two inputs and return either True or False . The table below shows three logical operators.

Note : You will see in some code examples here and elsewhere the logic operators and and or replaced by something called bitwise operators: & used instead of and and | instead of or . Note that, even if they give the same results when applied to boolean data types (as in the examples above), they have different meanings for other data types. We will use mostly and and or in this textbook.

Finally, an expression can contain multiple comparisons, and all comparisons must hold in order for the whole expression to be True. You can see a couple of examples below. In the first, Python evaluates first the expression 5-2 (equal to 3 ), then evaluates 1.2 <= 1.8 and 1.8 < 3 (both True), and finally use the boolean operator and to evaluate the full expression.

## Truth tables #

An easy way to summarize the outcome of logic operators are truth tables, and we show them below for and and or . Note that we used them in the multiple comparisons above. They are useful for algorithmic thinking in programming. For simplicity we summarize them in a single table.

## C++ Operator Overloading Guidelines

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading . You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.

- = (assignment operator)
- + - * (binary arithmetic operators)
- += -= *= (compound assignment operators)
- == != (comparison operators)

Here are some guidelines for implementing these operators. These guidelines are very important to follow, so definitely get in the habit early.

## Assignment Operator =

The assignment operator has a signature like this: class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } MyClass a, b; ... b = a; // Same as b.operator=(a);

Notice that the = operator takes a const-reference to the right hand side of the assignment. The reason for this should be obvious, since we don't want to change that value; we only want to change what's on the left hand side.

- e = 42 assigns 42 to e , then returns e as the result
- The value of e is then assigned to d , and then d is returned as the result
- The value of d is then assigned to c , and then c is returned as the result

Now, in order to support operator chaining, the assignment operator must return some value. The value that should be returned is a reference to the left-hand side of the assignment.

Notice that the returned reference is not declared const . This can be a bit confusing, because it allows you to write crazy stuff like this: MyClass a, b, c; ... (a = b) = c; // What?? At first glance, you might want to prevent situations like this, by having operator= return a const reference. However, statements like this will work with primitive types. And, even worse, some tools actually rely on this behavior. Therefore, it is important to return a non- const reference from your operator= . The rule of thumb is, "If it's good enough for int s, it's good enough for user-defined data-types."

So, for the hypothetical MyClass assignment operator, you would do something like this: // Take a const-reference to the right-hand side of the assignment. // Return a non-const reference to the left-hand side. MyClass& MyClass::operator=(const MyClass &rhs) { ... // Do the assignment operation! return *this; // Return a reference to myself. } Remember, this is a pointer to the object that the member function is being called on. Since a = b is treated as a.operator=(b) , you can see why it makes sense to return the object that the function is called on; object a is the left-hand side.

But, the member function needs to return a reference to the object, not a pointer to the object. So, it returns *this , which returns what this points at (i.e. the object), not the pointer itself. (In C++, instances are turned into references, and vice versa, pretty much automatically, so even though *this is an instance, C++ implicitly converts it into a reference to the instance.)

Now, one more very important point about the assignment operator:

YOU MUST CHECK FOR SELF-ASSIGNMENT!

This is especially important when your class does its own memory allocation. Here is why: The typical sequence of operations within an assignment operator is usually something like this: MyClass& MyClass::operator=(const MyClass &rhs) { // 1. Deallocate any memory that MyClass is using internally // 2. Allocate some memory to hold the contents of rhs // 3. Copy the values from rhs into this instance // 4. Return *this } Now, what happens when you do something like this: MyClass mc; ... mc = mc; // BLAMMO. You can hopefully see that this would wreak havoc on your program. Because mc is on the left-hand side and on the right-hand side, the first thing that happens is that mc releases any memory it holds internally. But, this is where the values were going to be copied from, since mc is also on the right-hand side! So, you can see that this completely messes up the rest of the assignment operator's internals.

The easy way to avoid this is to CHECK FOR SELF-ASSIGNMENT. There are many ways to answer the question, "Are these two instances the same?" But, for our purposes, just compare the two objects' addresses. If they are the same, then don't do assignment. If they are different, then do the assignment.

So, the correct and safe version of the MyClass assignment operator would be this: MyClass& MyClass::operator=(const MyClass &rhs) { // Check for self-assignment! if (this == &rhs) // Same object? return *this; // Yes, so skip assignment, and just return *this. ... // Deallocate, allocate new space, copy values... return *this; } Or, you can simplify this a bit by doing: MyClass& MyClass::operator=(const MyClass &rhs) { // Only do assignment if RHS is a different object from this. if (this != &rhs) { ... // Deallocate, allocate new space, copy values... } return *this; } Remember that in the comparison, this is a pointer to the object being called, and &rhs is a pointer to the object being passed in as the argument. So, you can see that we avoid the dangers of self-assignment with this check.

- Take a const-reference for the argument (the right-hand side of the assignment).
- Return a reference to the left-hand side, to support safe and reasonable operator chaining. (Do this by returning *this .)
- Check for self-assignment, by comparing the pointers ( this to &rhs ).

## Compound Assignment Operators += -= *=

I discuss these before the arithmetic operators for a very specific reason, but we will get to that in a moment. The important point is that these are destructive operators, because they update or replace the values on the left-hand side of the assignment. So, you write: MyClass a, b; ... a += b; // Same as a.operator+=(b) In this case, the values within a are modified by the += operator.

How those values are modified isn't very important - obviously, what MyClass represents will dictate what these operators mean.

The member function signature for such an operator should be like this: MyClass & MyClass::operator+=(const MyClass &rhs) { ... } We have already covered the reason why rhs is a const-reference. And, the implementation of such an operation should also be straightforward.

But, you will notice that the operator returns a MyClass -reference, and a non-const one at that. This is so you can do things like this: MyClass mc; ... (mc += 5) += 3;

Don't ask me why somebody would want to do this, but just like the normal assignment operator, this is allowed by the primitive data types. Our user-defined datatypes should match the same general characteristics of the primitive data types when it comes to operators, to make sure that everything works as expected.

This is very straightforward to do. Just write your compound assignment operator implementation, and return *this at the end, just like for the regular assignment operator. So, you would end up with something like this: MyClass & MyClass::operator+=(const MyClass &rhs) { ... // Do the compound assignment work. return *this; }

As one last note, in general you should beware of self-assignment with compound assignment operators as well. Fortunately, none of the C++ track's labs require you to worry about this, but you should always give it some thought when you are working on your own classes.

## Binary Arithmetic Operators + - *

The binary arithmetic operators are interesting because they don't modify either operand - they actually return a new value from the two arguments. You might think this is going to be an annoying bit of extra work, but here is the secret:

Define your binary arithmetic operators using your compound assignment operators.

There, I just saved you a bunch of time on your homeworks.

So, you have implemented your += operator, and now you want to implement the + operator. The function signature should be like this: // Add this instance's value to other, and return a new instance // with the result. const MyClass MyClass::operator+(const MyClass &other) const { MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this); result += other; // Use += to add other to the copy. return result; // All done! } Simple!

Actually, this explicitly spells out all of the steps, and if you want, you can combine them all into a single statement, like so: // Add this instance's value to other, and return a new instance // with the result. const MyClass MyClass::operator+(const MyClass &other) const { return MyClass(*this) += other; } This creates an unnamed instance of MyClass , which is a copy of *this . Then, the += operator is called on the temporary value, and then returns it.

If that last statement doesn't make sense to you yet, then stick with the other way, which spells out all of the steps. But, if you understand exactly what is going on, then you can use that approach.

You will notice that the + operator returns a const instance, not a const reference. This is so that people can't write strange statements like this: MyClass a, b, c; ... (a + b) = c; // Wuh...? This statement would basically do nothing, but if the + operator returns a non- const value, it will compile! So, we want to return a const instance, so that such madness will not even be allowed to compile.

- Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators.
- Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed.

## Comparison Operators == and !=

The comparison operators are very simple. Define == first, using a function signature like this: bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. } The internals are very obvious and straightforward, and the bool return-value is also very obvious.

The important point here is that the != operator can also be defined in terms of the == operator, and you should do this to save effort. You can do something like this: bool MyClass::operator!=(const MyClass &other) const { return !(*this == other); } That way you get to reuse the hard work you did on implementing your == operator. Also, your code is far less likely to exhibit inconsistencies between == and != , since one is implemented in terms of the other.

Currently Reading :

Currently reading:

## What Are Python Operators?

Python operators.

Harsh Pandey

Software Developer

Published on Tue Mar 19 2024

Python, one of the most popular programming languages today, is known for its simplicity and readability. One fundamental aspect of Python that contributes to its ease of use is its operators. Operators are the constructs which can manipulate the value of operands. In this blog, we'll explore the different types of operators available in Python and their applications.

Operators in Python are special symbols or keywords that are used to perform operations on one or more operands. An operand can be a value, a variable, or an expression. Operators are the building blocks of Python programs and are used to perform tasks like arithmetic calculations, logical comparisons, and memory operations.

## Types Of Python Operators

The various types of operators in python are:

- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Identity Operators and Membership Operators

## Arithmetic Operators In Python

Arithmetic operators in Python are used to perform basic mathematical operations and are fundamental to any kind of numerical manipulation in Python programming. These operators include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//).

- Addition (+) Adds two operands. For example. result = 3 + 2 <br>print(result) # Output: 5
- Subtraction (-) Subtracts the right operand from the left operand. result = 5 - 3 <br>print(result) # Output: 2
- Multiplication (*) Multiplies two operands. result = 4 * 3 <br>print(result) # Output: 12
- Division (/) Divides the left operand by the right operand. The result is a floating-point number. result = 8 / 2 <br>print(result) # Output: 4 . 0
- Modulus (%) Returns the remainder of the division. result = 5 % 2 <br>print(result) # Output: 1
- Exponentiation (**) Raises the first operand to the power of the second operand. result = 3 ** 2 <br>print(result) # Output: 9
- Floor Division (//) Performs division but discards the fractional part, returning an integer result. result = 7 // 2 <br>print(result) # Output: 3

Understanding these arithmetic operators is essential for anyone beginning with Python, as they are used widely in various types of numerical calculations and data manipulation tasks.

## Comparison Operators In Python

Comparison operators in Python are used to compare values. They evaluate to either True or False based on the condition. These operators are essential in decision-making processes in Python scripts.

- Equal to (==) Checks if the values of two operands are equal. print (5 == 5) # Output: True <br> print (5 == 3) # Output: False
- Not Equal to (!=) Checks if the values of two operands are not equal. print (5 != 3) # Output: True <br> print (5 != 5) # Output: False
- Greater than (>) Checks if the value of the left operand is greater than the right operand. print (5 > 3) # Output: True <br> print (3 > 5) # Output: False
- Less than (<) Checks if the value of the left operand is less than the right operand. print (3 < 5) # Output: True <br> print (5 < 3) # Output: False
- Greater than or Equal to (>=) Checks if the left operand is greater than or equal to the right operand. print (5 >= 5) # Output: True <br> print (4 >= 5) # Output: False
- Less than or Equal to (<=) Checks if the left operand is less than or equal to the right operand. print (3 <= 5) # Output: True <br> print (5 <= 3) # Output: False

Understanding these comparison operators is crucial for controlling the flow of a Python program, as they are commonly used in conditional statements and loops to evaluate conditions and make decisions.

## Logical Operators In Python

Logical operators in Python are used to combine conditional statements, and they are fundamental in controlling the flow of logic in Python code. These operators include and, or, and not, each serving a specific purpose in evaluating conditions.

- and Operator The and operator returns True if both the operands (conditions) are true. print (( 5 > 3 ) and ( 5 > 4 )) # Output: True<br>print(( 5 > 3 ) and ( 5 < 4 )) # Output: False
- or Operator The or operator returns True if at least one of the operands is true. print (( 5 > 3 ) or ( 5 < 4 )) # Output: True<br>print(( 5 < 3 ) or ( 5 < 4 )) # Output: False
- not Operator The not operator reverses the result of the condition. It returns True if the condition is false and vice versa. print ( not (5 > 3)) # Output: False <br> print ( not (5 < 3)) # Output: True

Logical operators are integral in Python for building complex logical expressions, making them essential in decision-making structures like if-else statements and loops.

## Bitwise Operators In Python

Bitwise operators in Python are used to perform operations on binary numbers at the bit level. These operators are essential for manipulating individual bits and performing bit-by-bit operations.

- AND Operator (&) The & operator performs a bitwise AND, where each bit of the output is 1 if both corresponding bits of the operand are 1. print ( 5 & 3 ) # Output: 1
- OR Operator (|) The | operator performs a bitwise OR, where each bit of the output is 1 if at least one of the corresponding bits of the operands is 1. print ( 5 | 3 ) # Output: 7
- XOR Operator (^) The ^ operator performs a bitwise XOR, where each bit of the output is 1 if the corresponding bits of the operands are different. print ( 5 ^ 3 ) # Output: 6
- NOT Operator (~) The ~ operator performs a bitwise NOT, inverting each bit of the number. print (~ 5 ) # Output: -6
- Shift Operators Left Shift (<<): Shifts the bits of the number to the left and fills 0 on voids left as a result. The left operand specifies the value to be shifted, and the right operand specifies the number of positions to shift. print ( 5 << 1 ) # Output: 10 Right Shift (>>): Shifts the bits of the number to the right. The left operand specifies the value to be shifted, and the right operand specifies the number of positions to shift. print ( 5 >> 1 ) # Output: 2

Bitwise operators are particularly useful in low-level programming, such as device driver writing or protocol development, where manipulation of data at the bit level is crucial.

## Assignment Operator In Python

Assignment operators in Python are used to assign values to variables. These operators make the code more concise and improve its readability by combining arithmetic operations with assignment.

- The Basic Assignment Operator (=) The = operator assigns the value on the right to the variable on the left. x = 10 <br>print(x) # Output: 10
- Compound Assignment Operators These operators combine assignment with other operations. Add and Assign (+=): Adds the right operand to the left operand and assigns the result to the left operand. x = 5 < br > x + = 3 # Same as x = x + 3 < br >print( x ) # Output: 8 Subtract and Assign (-=): Subtracts the right operand from the left operand and assigns the result to the left operand. x = 5 < br > x - = 3 # Same as x = x - 3 < br >print( x ) # Output: 2 Multiply and Assign (*=): Multiplies the right operand with the left operand and assigns the result to the left operand. x = 5 < br > x * = 3 # Same as x = x * 3 < br >print( x ) # Output: 15 Divide and Assign (/=): Divides the left operand by the right operand and assigns the result to the left operand. x = 10 < br > x / = 2 # Same as x = x / 2 < br >print( x ) # Output: 5.0

Assignment operators are essential in Python for variable manipulation, simplifying expressions, and making code more efficient and easier to understand.

## Identity Operators And Membership Operators In Python

Identity and Membership operators in Python are used to compare the identity of objects and check for membership within data structures, respectively.

## Identity Operators

Identity operators compare the memory locations of two objects. There are two identity operators in Python: is and is not.

- is: Evaluates to true if the variables on either side of the operator point to the same object. x = [ "apple" , "banana" ]< br >y = x < br >print( x is y) # Output: True
- is not: Evaluates to true if the variables on either side of the operator do not point to the same object. x = [ "apple" , "banana" ]< br >y = [ "apple" , "banana" ]< br >print( x is not y) # Output: True

## Membership Operators

Membership operators test if a sequence is presented in an object. The two membership operators in Python are in and not in.

- in: Returns True if a sequence with the specified value is present in the object. x = [ "apple" , "banana" ]<br>print( "banana" in x) # Output: True
- not in: Returns True if a sequence with the specified value is not present in the object. print ( "cherry" not in x) # Output: True

Identity and Membership operators are crucial in Python for validating the identity of objects and checking for the presence of elements within various data structures like lists, tuples, and strings. They are widely used in conditional statements and loops to enhance the logic and functionality of Python scripts.

Operators in Python are essential for performing various operations on data. Understanding these operators and their applications is crucial for anyone looking to master Python programming. Whether it's for data manipulation, arithmetic calculations, or logical comparisons, Python operators provide a simple yet powerful tool for developers.

## About the author

Software Developer adept in crafting efficient code and solving complex problems. Passionate about technology and continuous learning.

## Related Blogs

Python Output Formatting

Python print() Function

N-Gram Language Modelling with NLTK Using Python

Bisection Method In Python

How to Print to stderr and stdout in Python?

How to Check if an Item is in a List in Python

## Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your project.

- Programmers
- React Native
- Ruby on Rails

## Learn JavaScript Operators – Logical, Comparison, Ternary, and More JS Operators With Examples

JavaScript has many operators that you can use to perform operations on values and variables (also called operands)

Based on the types of operations these JS operators perform, we can divide them up into seven groups:

## Arithmetic Operators

Assignment operators, comparison operators, logical operators.

- Ternary Operators

## The typeof Operator

Bitwise operators.

In this handbook, you're going to learn how these operators work with examples. Let's start with arithmetic operators.

The arithmetic operators are used to perform mathematical operations like addition and subtraction.

These operators are frequently used with number data types, so they are similar to a calculator. The following example shows how you can use the + operator to add two variables together:

Here, the two variables x and y are added together using the plus + operator. We also used the console.log() method to print the result of the operation to the screen.

You can use operators directly on values without assigning them to any variable too:

In JavaScript, we have 8 arithmetic operators in total. They are:

- Subtraction -
- Multiplication *
- Remainder %
- Exponentiation **
- Increment ++
- Decrement --

Let's see how these operators work one by one.

## 1. Addition operator

The addition operator + is used to add two or more numbers together. You've seen how this operator works previously, but here's another example:

You can use the addition operator on both integer and floating numbers.

## 2. Subtraction operator

The subtraction operator is marked by the minus sign − and you can use it to subtract the right operand from the left operand.

For example, here's how to subtract 3 from 5:

## 3. Multiplication operator

The multiplication operator is marked by the asterisk * symbol, and you use it to multiply the value on the left by the value on the right of the operator.

## 4. Division operator

The division operator / is used to divide the left operand by the right operand. Here are some examples of using the operator:

## 5. Remainder operator

The remainder operator % is also known as the modulo or modulus operator. This operator is used to calculate the remainder after a division has been performed.

A practical example should make this operator easier to understand, so let's see one:

The number 10 can't be divided by 3 perfectly. The result of the division is 3 with a remainder of 1. The remainder operator simply returns that remainder number.

If the left operand can be divided with no remainder, then the operator returns 0.

This operator is commonly used when you want to check if a number is even or odd. If a number is even, dividing it by 2 will result in a remainder of 0, and if it's odd, the remainder will be 1.

## 6. Exponentiation operator

The exponentiation operator is marked by two asterisks ** . It's one of the newer JavaScript operators and you can use it to calculate the power of a number (based on its exponent).

For example, here's how to calculate 10 to the power of 3:

Here, the number 10 is multiplied by itself 3 times (10 _ 10 _ 10)

The exponentiation operator gives you an easy way to find the power of a specific number.

## 7. Increment operator

The increment ++ operator is used to increase the value of a number by one. For example:

This operator gives you a faster way to increase a variable value by one. Without the operator, here's how you increment a variable:

Using the increment operator allows you to shorten the second line. You can place this operator before or next to the variable you want to increment:

Both placements shown above are valid. The difference between prefix (before) and postfix (after) placements is that the prefix position will execute the operator after that line of code has been executed.

Consider the following example:

Here, you can see that placing the increment operator next to the variable will print the variable as if it has not been incremented.

When you place the operator before the variable, then the number will be incremented before calling the console.log() method.

## 8. Decrement operator

The decrement -- operator is used to decrease the value of a number by one. It's the opposite of the increment operator:

Please note that you can only use increment and decrement operators on a variable. An error occurs when you try to use these operators directly on a number value:

You can't use increment or decrement operator on a number directly.

## Arithmetic operators summary

Now you've learned the 8 types of arithmetic operators. Excellent! Keep in mind that you can mix these operators to perform complex mathematical equations.

For example, you can perform an addition and multiplication on a set of numbers:

The order of operations in JavaScript is the same as in mathematics. Multiplication, division, and exponentiation take a higher priority than addition or subtraction (remember that acronym PEMDAS? Parentheses, exponents, multiplication and division, addition and subtraction – there's your order of operations).

You can use parentheses () to change the order of the operations. Wrap the operation you want to execute first as follows:

When using increment or decrement operators together with other operators, you need to place the operators in a prefix position as follows:

This is because a postfix increment or decrement operator will not be executed together with other operations in the same line, as I have explained previously.

Let's try some exercises. Can you guess the result of these operations?

And that's all for arithmetic operators. You've done a wonderful job learning about these operators.

Let's take a short five-minute break before proceeding to the next type of operators.

The second group of operators we're going to explore is the assignment operators.

Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before:

After the basic assignment operator, there are 5 more assignment operators that combine mathematical operations with the assignment. These operators are useful to make your code clean and short.

For example, suppose you want to increment the x variable by 2. Here's how you do it with the basic assignment operator:

There's nothing wrong with the code above, but you can use the addition assignment += to rewrite the second line as follows:

There are 7 kinds of assignment operators that you can use in JavaScript:

The arithmetic operators you've learned in the previous section can be combined with the assignment operator except the increment and decrement operators.

Let's have a quick exercise. Can you guess the results of these assignments?

Now you've learned about assignment operators. Let's continue and learn about comparison operators.

As the name implies, comparison operators are used to compare one value or variable with something else. The operators in this category always return a boolean value: either true or false .

For example, suppose you want to compare if a variable's value is greater than 1. Here's how you do it:

The greater than > operator checks if the value on the left operand is greater than the value on the right operand.

There are 8 kinds of comparison operators available in JavaScript:

Here are some examples of using comparison operators:

The comparison operators are further divided in two types: relational and equality operators.

The relational operators compare the value of one operand relative to the second operand (greater than, less than)

The equality operators check if the value on the left is equal to the value on the right. They can also be used to compare strings like this:

String comparisons are case-sensitive, as shown in the example above.

JavaScript also has two versions of the equality operators: loose and strict.

In strict mode, JavaScript will compare the values without performing a type coercion. To enable strict mode, you need to add one more equal = symbol to the operation as follows:

Since type coercion might result in unwanted behavior, you should use the strict equality operators anytime you do an equality comparison.

Logical operators are used to check whether one or more expressions result in either true or false .

There are three logical operators available in JavaScript:

These operators can only return Boolean values. For example, you can determine whether '7 is greater than 2' and '5 is greater than 4':

These logical operators follow the laws of mathematical logic:

- && AND operator – if any expression returns false , the result is false
- || OR operator – if any expression returns true , the result is true
- ! NOT operator – negates the expression, returning the opposite.

Let's do a little exercise. Try to run these statements on your computer. Can you guess the results?

These logical operators will come in handy when you need to assert that a specific requirement is fulfilled in your code.

Let's say a happyLife requires a job with highIncome and supportiveTeam :

Based on the requirements, you can use the logical AND operator to check whether you have both requirements. When one of the requirements is false , then happyLife equals false as well.

## Ternary Operator

The ternary operator (also called the conditional operator) is the only JavaScipt operator that requires 3 operands to run.

Let's imagine you need to implement some specific logic in your code. Suppose you're opening a shop to sell fruit. You give a $3 discount when the total purchase is $20 or more. Otherwise, you give a $1 discount.

You can implement the logic using an if..else statement as follows:

The code above works fine, but you can use the ternary operator to make the code shorter and more concise as follows:

The syntax for the ternary operator is condition ? expression1 : expression2 .

You need to write the condition to evaluate followed by a question ? mark.

Next to the question mark, you write the expression to execute when the condition evaluates to true , followed by a colon : symbol. You can call this expression1 .

Next to the colon symbol, you write the expression to execute when the condition evaluates to false . This is expression2 .

As the example above shows, the ternary operator can be used as an alternative to the if..else statement.

The typeof operator is the only operator that's not represented by symbols. This operator is used to check the data type of the value you placed on the right side of the operator.

Here are some examples of using the operator:

The typeof operator returns the type of the data as a string. The 'number' type represents both integer and float types, the string and boolean represent their respective types.

Arrays, objects, and the null value are of object type, while undefined has its own type.

Bitwise operators are operators that treat their operands as a set of binary digits, but return the result of the operation as a decimal value.

These operators are rarely used in web development, so you can skip this part if you only want to learn practical stuff. But if you're interested to know how they work, then let me show you an example.

A computer uses a binary number system to store decimal numbers in memory. The binary system only uses two numbers, 0 and 1, to represent the whole range of decimal numbers we humans know.

For example, the decimal number 1 is represented as binary number 00000001, and the decimal number 2 is represented as 00000010.

I won't go into detail on how to convert a decimal number into a binary number as that's too much to include in this guide. The main point is that the bitwise operators operate on these binary numbers.

If you want to find the binary number from a specific decimal number, you can Google for the "decimal to binary calculator".

There are 7 types of bitwise operators in JavaScript:

- Left Shift <<
- Right Shift >>
- Zero-fill Right Shift >>>

Let's see how they work.

## 1. Bitwise AND operator

The bitwise operator AND & returns a 1 when the number 1 overlaps in both operands. The decimal numbers 1 and 2 have no overlapping 1, so using this operator on the numbers return 0:

## 2. Bitwise OR operator

On the other hand, the bitwise operator OR | returns all 1s in both decimal numbers.

The binary number 00000011 represents the decimal number 3, so the OR operator above returns 3.

## Bitwise XOR operator

The Bitwise XOR ^ looks for the differences between two binary numbers. When the corresponding bits are the same, it returns 0:

5 = 00000101

## Bitwise NOT operator

Bitwise NOT ~ operator inverts the bits of a decimal number so 0 becomes 1 and 1 becomes 0:

## Bitwise Left Shift operator

Bitwise Left Shift << shifts the position of the bit by adding zeroes from the right.

The excess bits are then discarded, changing the decimal number represented by the bits. See the following example:

The right operand is the number of zeroes you will add to the left operand.

## Bitwise Right Shift operator

Bitwise Right Shift >> shifts the position of the bits by adding zeroes from the left. It's the opposite of the Left Shift operator:

## Bitwise Zero-fill Right Shift operator

Also known as Unsigned Right Shift operator, the Zero-fill Right Shift >>> operator is used to shift the position of the bits to the right, while also changing the sign bit to 0 .

This operator transforms any negative number into a positive number, so you can see how it works when passing a negative number as the left operand:

In the above example, you can see that the >> and >>> operators return different results. The Zero-fill Right Shift operator has no effect when you use it on a positive number.

Now you've learned how the bitwise operators work. If you think they are confusing, then you're not alone! Fortunately, these operators are scarcely used when developing web applications.

You don't need to learn them in depth. It's enough to know what they are.

In this tutorial, you've learned the 7 types of JavaScript operators: Arithmetic, assignment, comparison, logical, ternary, typeof, and bitwise operators.

These operators can be used to manipulate values and variables to achieve a desired outcome.

Congratulations on finishing this guide!

If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here .

The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.

Here's my promise: You will actually feel like you understand what you're doing with JavaScript.

Until next time!

JavaScript Full Stack Developer currently working with fullstack JS using React and Express. Nathan loves to write about his experience in programming to help other people.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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

## What are Operators in Programming?

- Binary Operators in Programming
- Unary Operators in Programming
- Types of Operators in Programming
- Assignment Operators in Programming
- Comparison Operators in Programming
- Ternary Operator in Programming
- Bitwise AND operator in Programming
- Bitwise OR Operator (|) in Programming
- Logical AND operator in Programming
- Conditional Operator in Programming
- Right Shift Operator (>>) in Programming
- Modulus Operator in Programming
- Operator Associativity in Programming
- Logical NOT Operator in Programming
- Pre and Post Decrement Operator in Programming
- Increment and Decrement Operators in Programming
- Logical OR operator in Programming
- Operator Overloading in Dart
- Relational Operators in C

Operators in programming are essential symbols that perform operations on variables and values , enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types.

Operators in Programming

Table of Content

- Operator Precedence and Associativity in Programming
- Frequently Asked Questions (FAQs) related to Programming Operators

Operators in programming are symbols or keywords that represent computations or actions performed on operands. Operands can be variables , constants , or values , and the combination of operators and operands form expressions. Operators play a crucial role in performing various tasks, such as arithmetic calculations, logical comparisons, bitwise operations, etc.

## Types of Operators in Programming:

Here are some common types of operators:

- Arithmetic Operators: Perform basic arithmetic operations on numeric values. Examples: + (addition), – (subtraction), * (multiplication), / (division), % (modulo).
- Comparison Operators: Compare two values and return a Boolean result (true or false). Examples: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to).
- Logical Operators: Perform logical operations on Boolean values. Examples: && (logical AND), || (logical OR), ! (logical NOT).
- Assignment Operators: Assign values to variables. Examples: = (assign), += (add and assign), -=, *= (multiply and assign), /=, %=.
- Increment and Decrement Operators: Increase or decrease the value of a variable by 1. Examples: ++ (increment), — (decrement).
- Bitwise Operators: Perform operations on individual bits of binary representations of numbers. Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >> (right shift).

These operators provide the building blocks for creating complex expressions and performing diverse operations in programming languages. Understanding their usage is crucial for writing efficient and expressive code.

## Arithmetic Operators in Programming:

Arithmetic operators in programming are fundamental components of programming languages, enabling the manipulation of numeric values for various computational tasks. Here’s an elaboration on the key arithmetic operators:

## Comparison Operators in Programming:

Comparison operators in programming are used to compare two values or expressions and return a Boolean result indicating the relationship between them. These operators play a crucial role in decision-making and conditional statements. Here are the common comparison operators:

These operators are extensively used in conditional statements, loops, and decision-making constructs to control the flow of a program based on the relationship between variables or values. Understanding comparison operators is crucial for creating logical and effective algorithms in programming.

## Logical Operators in Programming:

Logical operators in programming are used to perform logical operations on Boolean values . These operators are crucial for combining or manipulating conditions and controlling the flow of a program based on logical expressions. Here are the common logical operators:

These logical operators are frequently used in conditional statements (if, else if, else), loops, and decision-making constructs to create complex conditions based on multiple Boolean expressions. Understanding how to use logical operators is essential for designing effective and readable control flow in programming.

## Assignment Operators in Programming:

Assignment operators in programming are used to assign values to variables. They are essential for storing and updating data within a program. Here are common assignment operators:

Assignment operators are fundamental for updating variable values, especially in loops and mathematical computations, contributing to the dynamic nature of programming. Understanding how to use assignment operators is essential for effective variable manipulation in a program.

## Increment and Decrement Operators in Programming:

Increment and decrement operators in programming are used to increase or decrease the value of a variable by 1, respectively. They are shorthand notations for common operations and are particularly useful in loops. Here are the two types:

These operators are frequently employed in loops, especially for iterating through arrays or performing repetitive tasks. Their concise syntax enhances code readability and expressiveness.

## Bitwise Operators in Programming:

Bitwise operators in programming perform operations at the bit level , manipulating individual bits of binary representations of numbers. These operators are often used in low-level programming, such as embedded systems and device drivers. Here are the common bitwise operators:

Bitwise operators are useful in scenarios where direct manipulation of binary representations or specific bit patterns is required, such as optimizing certain algorithms or working with hardware interfaces. Understanding bitwise operations is essential for low-level programming tasks.

## Operator Precedence and Associativity in Programming :

Operator Precedence is a rule that determines the order in which operators are evaluated in an expression. It defines which operators take precedence over others when they are combined in the same expression. Operators with higher precedence are evaluated before operators with lower precedence. Parentheses can be used to override the default precedence and explicitly specify the order of evaluation.

Operator Associativity is a rule that determines the grouping of operators with the same precedence in an expression when they appear consecutively. It specifies the direction in which operators of equal precedence are evaluated. The two common associativities are:

- Left to Right (Left-Associative): Operators with left associativity are evaluated from left to right. For example, in the expression a + b + c , the addition operators have left associativity, so the expression is equivalent to (a + b) + c .
- Right to Left (Right-Associative): Operators with right associativity are evaluated from right to left. For example, in the expression a = b = c , the assignment operator = has right associativity, so the expression is equivalent to a = (b = c) .

## Frequently Asked Questions (FAQs) related to Programming Operators :

Here are some frequently asked questions (FAQs) related to programming operators:

## Q1: What are operators in programming?

A: Operators in programming are symbols that represent computations or actions to be performed on operands. They can manipulate data, perform calculations, and facilitate various operations in a program.

## Q2: How are operators categorized?

A: Operators are categorized based on their functionality. Common categories include arithmetic operators (for mathematical operations), assignment operators (for assigning values), comparison operators (for comparing values), logical operators (for logical operations), and bitwise operators (for manipulating individual bits).

## Q3: What is the difference between unary and binary operators?

A: Unary operators operate on a single operand, while binary operators operate on two operands. For example, the unary minus -x negates the value of x , while the binary plus a + b adds the values of a and b .

## Q4: Can operators be overloaded in programming languages?

A: Yes, some programming languages support operator overloading, allowing developers to define custom behaviors for operators when applied to user-defined types. This is commonly seen in languages like C++.

## Q5: How do logical AND ( && ) and logical OR ( || ) operators work?

A: The logical AND ( && ) operator returns true if both of its operands are true. The logical OR ( || ) operator returns true if at least one of its operands is true. These operators are often used in conditional statements and expressions.

## Q6: What is the purpose of the ternary operator ( ?: )?

A: The ternary operator is a shorthand for an if-else statement. It evaluates a condition and returns one of two values based on whether the condition is true or false. It is often used for concise conditional assignments.

## Q7: How does the bitwise XOR operator ( ^ ) work?

A: The bitwise XOR ( ^ ) operator performs an exclusive OR operation on individual bits. It returns 1 for bits that are different and 0 for bits that are the same. This operator is commonly used in bit manipulation tasks.

## Q8: What is the difference between = and == ?

A: The = operator is an assignment operator used to assign a value to a variable. The == operator is a comparison operator used to check if two values are equal. It is important not to confuse the two, as = is used for assignment, and == is used for comparison.

## Q9: How do increment ( ++ ) and decrement ( -- ) operators work?

A: The increment ( ++ ) operator adds 1 to the value of a variable, while the decrement ( -- ) operator subtracts 1. These operators can be used as prefix ( ++x ) or postfix ( x++ ), affecting the order of the increment or decrement operation.

## Q10: Are operators language-specific?

A: While many operators are common across programming languages, some languages may introduce unique operators or have variations in their behavior. However, the fundamental concepts of arithmetic, logical, and bitwise operations are prevalent across various languages.

## Q11: What is the modulus operator ( % ) used for?

A: The modulus operator ( % ) returns the remainder when one number is divided by another. It is often used to check divisibility or to cycle through a sequence of values. For example, a % 2 can be used to determine if a is an even or odd number.

## Q12: Can the same operator have different meanings in different programming languages?

A: Yes, the same symbol may represent different operators or operations in different programming languages. For example, the + operator is used for addition in most languages, but in some languages (like JavaScript), it is also used for string concatenation.

## Q13: What is short-circuit evaluation in the context of logical operators?

A: Short-circuit evaluation is a behavior where the second operand of a logical AND ( && ) or logical OR ( || ) operator is not evaluated if the outcome can be determined by the value of the first operand alone. This can lead to more efficient code execution.

## Q14: How are bitwise left shift ( << ) and right shift ( >> ) operators used?

A: The bitwise left shift ( << ) operator shifts the bits of a binary number to the left, effectively multiplying the number by 2. The bitwise right shift ( >> ) operator shifts the bits to the right, effectively dividing the number by 2.

## Q15: Can you provide an example of operator precedence in programming?

A: Operator precedence determines the order in which operators are evaluated. For example, in the expression a + b * c , the multiplication ( * ) has higher precedence than addition ( + ), so b * c is evaluated first.

## Q16: How does the ternary operator differ from an if-else statement?

A: The ternary operator ( ?: ) is a concise way to express a conditional statement with a single line of code. It returns one of two values based on a condition. An if-else statement provides a more extensive code block for handling multiple statements based on a condition.

## Q17: Are there any operators specifically designed for working with arrays or collections?

A: Some programming languages provide specific operators or methods for working with arrays or collections. For example, in Python, the in operator is used to check if an element is present in a list.

## Q18: How can bitwise operators be used for efficient memory management?

A: Bitwise operators are often used for efficient memory management by manipulating individual bits. For example, bitwise AND can be used to mask specific bits, and bitwise OR can be used to set particular bits.

## Q19: Can operators be overloaded in all programming languages?

A: No, not all programming languages support operator overloading. While some languages like C++ allow developers to redefine the behavior of operators for user-defined types, others, like Java, do not permit operator overloading.

## Q20: How do you handle operator precedence in complex expressions?

A: Parentheses are used to explicitly specify the order of operations in complex expressions, ensuring that certain operations are performed before others. For example, (a + b) * c ensures that addition is performed before multiplication.

In conclusion, operators in programming are essential tools that enable the manipulation, comparison, and logical operations on variables and values. They form the building blocks of expressions and play a fundamental role in controlling program flow, making decisions, and performing calculations. From arithmetic and comparison operators for numerical tasks to logical operators for decision-making, and bitwise operators for low-level bit manipulation, each type serves specific purposes in diverse programming scenarios.

## Please Login to comment...

Similar reads.

- Programming

## Improve your Coding Skills with Practice

## What kind of Experience do you want to share?

- Español – América Latina
- Português – Brasil
- Tiếng Việt

## Comparison operators

Comparison operators compare the values of two operands and evaluate whether the statement they form is true or false . The following example uses the strict equality operator ( === ) to compare two operands: the expression 2 + 2 and the value 4 . Because the result of the expression and the number value 4 are the same, this expression evaluates to true :

## Type coercion and equality

Two of the most frequently-used comparison operators are == for loose equality and === for strict equality. == performs a loose comparison between two values by coercing the operands to matching data types, if possible. For example, 2 == "2" returns true , even though the comparison is being made between a number value and a string value.

The same is true of != , which returns true only if the operands being compared aren't loosely equal.

Strict comparisons using === or !== don't perform type coercion. For a strict comparison to evaluate to true , the values being compared must have the same data type. Because of this, 2 == "2" returns true , but 2 === "2" returns false :

To remove any ambiguity that might result from auto-coercion, use === whenever possible.

## Truthy and falsy

All values in JavaScript are implicitly true or false , and can be coerced to the corresponding boolean value—for example, by using the "loosely equal" comparator. A limited set of values coerce to false :

- An empty string ( "" )

All other values coerce to true , including any string containing one or more characters and all nonzero numbers. These are commonly called "truthy" and "falsy" values.

## Logical operators

Use the logical AND ( && ), OR ( || ), and NOT ( ! ) operators to control the flow of a script based on the evaluation of two or more conditional statements:

A logical NOT ( ! ) expression negates the truthy or falsy value of an operand, evaluating to true if the operand evaluates to false , and false if the operand evaluates to true :

Using the logical NOT operator ( ! ) in front of another data type, like a number or a string, coerces that value to a boolean and reverses the truthy or falsy value of the result.

It's common practice to use two NOT operators to quickly coerce data to its matching boolean value:

The logical AND and OR operators don't perform any coercion by themselves. They return the value of one of the two operands being evaluated, with the chosen operand determined by that evaluation.

Logical AND ( && ) returns the first of its two operands only if that operand evaluates to false , and the second operand otherwise. In comparisons that evaluate to boolean values, it returns true only if the operands on both sides of the logical AND evaluate to true . If either side evaluates to false , it returns false .

When && is used with two non-boolean operands, the first operand is returned unchanged if it can be coerced to false . If the first operand can be coerced to true , the second operand is returned unchanged:

Logical OR ( || ) returns the first of its two operands only if that operand evaluates to true , and the second operand otherwise. In comparisons that evaluate to boolean values, this means it returns true if either operand evaluates to true , and if neither side evaluates to true , it returns false :

When using || with two non-boolean operands, it returns the first operand unchanged if it could be coerced to true . If the first operand can be coerced to false , the second operand is returned unchanged:

## Nullish coalescing operator

Introduced in ES2020 , the "nullish coalescing operator" ( ?? ) returns the first operand only if that operand has any value other than null or undefined . Otherwise, it returns the second operand.

?? is similar to a logical OR, but stricter in how the first operand is evaluated. || returns the second operand for any expression that can be coerced to false , including undefined and null . ?? returns the second operand when the first operand is anything but null or undefined , even if it could be coerced to false :

## Logical assignment operators

Use assignment operators to assign the value of a second operator to a first operator. The most common example of this is a single equals sign ( = ), used to assign a value to a declared variable .

Use logical assignment operators to conditionally assign a value to a variable based on the truthy or falsy value of that variable.

The logical AND assignment ( &&= ) operator evaluates the second operand and assigns to the first operand if the only if the first operand would evaluate to true —effectively, "if the first operand is true, assign it the value of the second operand instead:"

The truthy or falsy value of the first operand determines whether an assignment is performed. However, trying to evaluate the first operand using a comparison operator results in a true or false boolean, which can't be assigned a value:

The logical OR assignment ( ||= ) operator evaluates the second operand and assign to the first operand if the first operand evaluates to false — effectively "if the first operand is false, assign it the value of the second operand instead:"

## Check your understanding

Which operator indicates "strictly equal"?

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-03-31 UTC.

## COMMENTS

A common syntax error experienced by beginner Python programmers is in using the assignment operator = instead of the equality operator == in a conditional expression:

The differences can be shown in tabular form as follows: =. ==. It is an assignment operator. It is a relational or comparison operator. It is used for assigning the value to a variable. It is used for comparing two values. It returns 1 if both the values are equal otherwise returns 0. Constant term cannot be placed on left hand side.

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

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

While comparison operators are used to compare values and return boolean results, assignment operators are used to assign values to variables. The key differences between comparison and assignment operators are as follows: Purpose: Comparison operators compare values and determine their relationship (equality, greater than, less than, etc.).

Python Identity Operators. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example. Try it. is. Returns True if both variables are the same object. x is y.

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

= is the assignment operator. It sets a variable (the left-hand side) to a value (the right-hand side). The result is the value on the right-hand side. == is the comparison operator. It will only return true if both values are equivalent after coercing their types to the same type. === is a more strict comparison operator often called the ...

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.

Comparison operators. Comparison operators are used to compare values using mathematical logic and return a single Boolean value of either True or False. We will see later that they are important for counting, extracting and modifying data. For example, counting the number of students with GPA higher than a given threshold requires a comparison ...

Comparison Operators in programming are used to compare values and determine their relationship, such as equality, inequality, greater than, less than, etc. They evaluate expressions and return a Boolean value (true or false) based on the comparison result, crucial for decision-making in conditional statements and loops. Table of Content.

Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators. Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed. Comparison Operators == and !=

These operators make the code more concise and improve its readability by combining arithmetic operations with assignment. The Basic Assignment Operator (=) The = operator assigns the value on the right to the variable on the left. x = 10 <br>print(x) # Output: 10; Compound Assignment Operators These operators combine assignment with other ...

Why two symbols when performing an equal to comparison? Because = is already being used as an assignment operator, e.g. a = 10 assigns the value 10 to the variable a. Logical operators In addition to comparing two or more values to one another when performing a test, we might want to perform multiple comparisons simultaneously.

The second group of operators we're going to explore is the assignment operators. Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before: let x = 5; After the basic assignment operator, there are 5 more ...

Operators in programming are symbols or keywords that represent computations or actions performed on operands. Operands can be variables, constants, or values, and the combination of operators and operands form expressions. Operators play a crucial role in performing various tasks, such as arithmetic calculations, logical comparisons, bitwise ...

Comparison operators compare the values of two operands and evaluate whether the statement they form is true or false.The following example uses the strict equality operator (===) to compare two operands: the expression 2 + 2 and the value 4.Because the result of the expression and the number value 4 are the same, this expression evaluates to true:. 2 + 2 === 4 > true

Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. Therefore it evaluates the right-hand side, apps["special_groups"] == group , first, and then it assigns this result to the left-hand side, group_index .

The assignment operator and the comparison operator are the same. The statement 15 >= -63 will result in the value True. The statement Set Cost = Price + Tax is an example of a comparison statement. A single-alternative selection structure always contains an Else clause.

Reference: JavaScript Tutorial: Comparison Operators. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

What I want to know if CategoryID=p.CategoryID is an assignment operator or a comparison operator? I mean does it mean if CategoryID=1 for example or does it return TRUE if both are same? Everywhere it is written = is a comparison operator in SQL. If it is a comparison operator and returning true, how it takes an average value of prices of a ...