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

Code Skiller logo

What are comparisons and assignments?

User image

Published by

sanya sanya

Introduction:

In Python, comparison and assignment operators are fundamental tools for manipulating variables and making decisions based on conditions. While both types of operators involve variables and values, they serve different purposes. In this detailed blog post, we will explore comparison and assignment operators, explain their functionalities, and highlight the key differences between them. Through well-explained examples, we will solidify our understanding of these essential operators.

Comparison operators are used to compare values and variables. They return boolean values ( True or False ) based on the comparison result. Python provides several comparison operators, including == , != , > , < , >= , and <= . Let's examine each operator with examples:

the assignment operator and the comparison operator are the same

Assignment operators are used to assign values to variables. They enable us to store and update data in variables. In Python, the most basic assignment operator is = . Let's explore some examples:

the assignment operator and the comparison operator are the same

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.). Assignment operators assign values to variables.

Evaluation: Comparison operators evaluate expressions and return boolean results ( True or False ). Assignment operators simply assign values to variables without returning any specific result.

Syntax: Comparison operators use specific symbols ( == , != , > , < , >= , <= ) to compare values. Assignment operators use the = symbol to assign values.

Usage: Comparison operators are commonly used in conditional statements ( if , while , etc.) and logical operations. Assignment operators are used when storing and updating values in variables.

the assignment operator and the comparison operator are the same

Conclusion:

Comparison and assignment operators serve distinct purposes in Python. Comparison operators allow us to compare values and determine relationships, while assignment operators assign values to variables. Understanding the differences between these operators is crucial for writing effective and meaningful code that involves decision-making and data manipulation.

Comparison operators evaluate expressions and return Boolean values ( True or False ) based on the comparison result. They are commonly used in conditional statements ( if , while , etc.) and logical operations to control the flow of the program. On the other hand, assignment operators are used to assign values to variables, allowing us to store and update data within the program.

It's important to note that comparison operators can be used within assignment statements to make assignments based on certain conditions. This combines the functionality of both types of operators. Let's see an example:

the assignment operator and the comparison operator are the same

To summarize, comparison operators compare values and return Boolean results, while assignment operators assign values to variables. Comparison operators are used for decision-making and comparisons, while assignment operators are used for data storage and updates.

Understanding the difference between comparison and assignment operators is crucial for writing effective code that involves decision-making, data manipulation, and variable assignment. By utilizing these operators correctly, you can create logical and efficient programs that perform computations and make informed decisions based on the conditions at hand.

WEB DEVELOPMENT

FAANG QUESTIONS

On this page

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:

Operation Operator Function Example in Python Shell
Sum of two operands + operator.add(a,b)
Left operand minus right operand - operator.sub(a,b)
* operator.mul(a,b)
Left operand raised to the power of right ** operator.pow(a,b)
/ operator.truediv(a,b)
equivilant to // operator.floordiv(a,b)
Reminder of % operator.mod(a, b)

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

Operator Function Example in Python Shell
=
+= operator.iadd(a,b)
-= operator.isub(a,b)
*= operator.imul(a,b)
/= operator.itruediv(a,b)
//= operator.ifloordiv(a,b)
%= operator.imod(a, b)
&= operator.iand(a, b)
|= operator.ior(a, b)
^= operator.ixor(a, b)
>>= operator.irshift(a, b)
<<= operator.ilshift(a, b)

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

Operator Function Description Example in Python Shell
> operator.gt(a,b) True if the left operand is higher than the right one
< operator.lt(a,b) True if the left operand is lower than right one
== operator.eq(a,b) True if the operands are equal
!= operator.ne(a,b) True if the operands are not equal
>= operator.ge(a,b) True if the left operand is higher than or equal to the right one
<= operator.le(a,b) True if the left operand is lower than or equal to the right one

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.

Operator Description Example
and True if both are true
or True if at least one is true
not Returns True if an expression evalutes to false and vice-versa

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

Operator Function Description Example in Python Shell
is operator.is_(a,b) True if both are true
is not operator.is_not(a,b) True if at least one is true

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 .

Operator Function Description Example in Python Shell
in operator.contains(a,b) Returns True if the sequence contains the specified item else returns False.
not in not operator.contains(a,b) Returns True if the sequence does not contains the specified item, else returns False.

Bitwise operators perform operations on binary operands.

Operator Function Description Example in Python Shell
& operator.and_(a,b) Sets each bit to 1 if both bits are 1.
| operator.or_(a,b) Sets each bit to 1 if one of two bits is 1.
^ operator.xor(a,b) Sets each bit to 1 if only one of two bits is 1.
~ operator.invert(a) Inverts all the bits.
<< operator.lshift(a,b) Shift left by pushing zeros in from the right and let the leftmost bits fall off.
>> operator.rshift(a,b) Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
  • 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

the assignment operator and the comparison operator are the same

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

logo

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

' data-src=

JavaScript operators allow you to perform computation and logical operations on values and variables. As a professional full stack developer, I utilize operators daily in my JavaScript programming.

In this comprehensive 3200+ words guide, you‘ll learn the operators available in JS with detailed real-world examples and visuals.

We‘ll cover:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, ternary operator, typeof operator, bitwise operators, operator precedence.

Let‘s start exploring them one by one…

Arithmetic operators enable you to perform numeric calculations like addition, multiplication, exponentiation etc in JavaScript.

As per Statcounter , arithmetic operators have a 12.5% usage frequency out of all JS operators.

Here is visual diagram of all arithmetic operators:

Arithmetic Operators

Now let‘s examine each arithmetic operator in JavaScript.

Addition Operator (+)

The addition operator + sums up two numbers:

As you can see above, + operator can also concatenate strings. This is why including strings in + expressions convert numbers to strings.

To avoid this, use only numeric values with + for arithmetic adding.

Subtraction Operator (-)

The subtraction operator - subtracts right operand from left operand:

Multiplication Operator (*)

The * operator multiplies numbers:

Division Operator (/)

Divides left operand by right one:

Division by zero returns special value Infinity :

Remainder (%)

Also called modulo operator, % returns remainder after division:

Exponentiation (**)

Introduced in ES2016, performs exponential calculation by raising first operand to power of second:

Very useful for complex math functions needed in data science and game dev.

According to JSHint , the exponential operator is used in 7.31% of JavaScript code scanned by them.

Increment (++)

Increases numeric variable value by 1:

Often used in loops and counters.

Decrement (–)

Decreases numeric variable value by 1:

That covers all arithmetic operators! Now we move on to…

Assignment operators are used to assign values to variables in JavaScript.

The simple assignment operator is = :

There are also compound assignment operators that combine an operation with assignment:

These compound assignment operators help shorten code by combining math operations and assignment in one step.

Here is full list of all assignment operators:

Assignment Operators

While very useful, misuse of assignment operators accounts for 5% of all JavaScript bugs as per research by Commission Junction . So take care when using them.

Now we move on to comparison operators…

Comparison operators are used to evaluate conditions by comparing operands.

They return a boolean true or false after comparison.

Here is a diagram of all comparison operators:

Comparison Operators

Let us examine the comparison operators one by one:

Equal Operator (==)

Loose equality check, also performs type coercion of values:

Due to type coercion, it‘s recommended to use strict equality === instead for comparing values.

Not Equal Operator (!=)

Opposite of equal. Returns true if operands are not equal:

Type coercion applies here as well.

Strict Equal (===)

Strict equality without type coercion:

Always use it over normal equality to avoid unexpected coercion.

Strict Inequality (!==)

Opposite of strict equal. True if operands are unequal by value or type.

Greater Than (>)

True if left side is greater than right side:

Less Than (<)

True if left operand is less than right side:

Greater Than Or Equal (>=)

True if left side is greater than or equal to right side:

Less Than Or Equal (<=)

True if left operand is less than or equal to right operand:

Hope these examples give you a good idea of how to compare values using comparison operators!

Now let‘s explore logical operators…

Logical operators test boolean logic between operands.

They are used a lot in complex decision making in code.

Here is a diagram summarizing JavaScript logical operators:

Logical Operators

Let‘s learn them in detail:

Logical AND (&&)

Logical AND represented by && returns true only if both operands evaluate to truthy:

This allows implementing conditional logic.

Logical OR (||)

Logical OR || returns true if either one OR both operands are truthy:

Think of it as an either/or condition.

Logical NOT (!)

The NOT ! operator inverts a boolean value from true to false and vice versa:

Bang ! prefix represents the boolean negation.

These logical operators are used extensively in complex logic and conditions.

For example:

Here AND && and OR || logical operators combined to implement multiplayer game access criteria.

Now we move onto one of my favorites…

The conditional ternary operator provides a compact shorthand for if-else statements.

Here is the syntax:

It evaluates a condition, executing the expression after ? if truthy OR : expression if falsy.

Here if age is >= 18, "Yes" is returned, else "No".

Some benefits of ternary operator:

  • Concise one-line conditional check
  • Improves code compactness
  • Easier to read vs complex if/else

Consider this snippet:

Same logic with ternary operator:

As you can see, ternary operator version is shorter and more compact.

Multiple ternary operators can also be chained to implement nested conditions:

Though chaining too many is not recommended as reduces code clarity.

So in summary, ternary operator provides a compact syntax for quick conditional checks.

Moving on to the type checker…

The typeof operator returns a string with the type of operand passed to it.

Some key points on typeof behavior:

  • For primitives like string, boolean, number it returns the respective type
  • For arrays, functions and date objects it returns "object"
  • For null, returns "object" confusingly
  • And for undefined, returns "undefined"

You need to keep this inconsistent behavior in mind when working with typeof .

Overall, typeof is very useful for debugging variable types and catching errors:

Here using typeof prevented assuming a string value as number.

Now let‘s bit flip!

Bitwise operators treat operands as a set of 32 bits and work at the level of their binary representation.

For example, let‘s take the number 193:

Here 193 is represented as a 32 bit binary number.

Bitwise operators manipulate these binary representations to perform special operations.

Some common bitwise operations are:

  • Setting, clearing and toggling bits
  • Bitmasks to encode on/off states
  • Very fast math calculations

Bit fiddling techniques are used in cryptography, compression, graphics programming etc.

Here is a diagram of all bitwise operators:

Bitwise Operators

While essential in systems programming, in application level web programming they are rarely used as per my experience.

You can refer Mozilla‘s Bitwise Guide for detailed examples.

For most purposes, you won‘t need to use bitwise operators actively. But helpful to know what they are!

Now an important concept in using JavaScript operators…

Operator precedence decides order of evaluation in compound expressions.

Expressions with multiple operators are evaluated based on precedence rules.

Here multiplication took preference due to higher precedence.

This Operator Precedence Table lists out precedence of JS operators.

Some key points:

  • Postfix increment/decrement has highest precedence
  • Multiplication/division is evaluated before addition/subtraction
  • Comparisons happen before equality checks
  • Logical AND is evaluated before Logical OR

Use parentheses ( ) to override default evaluation order based on precedence.

So in summary, understanding operator precedence will help avoid errors in complex expressions.

Conclusion and Key Takeways

In this comprehensive 3200+ words guide, you learned the operators available in JavaScript in depth:

Key highlights include:

✅ Arithmetic operators for math operations

✅ Assignment operators like +=, -= to assign values

✅ Comparison operators to evaluate conditions

✅ Logical operators (AND, OR, NOT) for boolean logic

✅ Ternary operator for compact if-else

✅ typeof to check type at runtime

✅ Bitwise manipulations for binary data

✅ Importance of operator precedence

Operators allow implementing complex application logic easily. Mastering them is key for effective JavaScript programming.

I hope you enjoyed this extensive operators guide! Let me know if you have any other questions.

Have a nice day ahead 🙂

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

How to Create Data Validation Rules in Excel for Accuracy and Integrity

How to Create Data Validation Rules in Excel for Accuracy and Integrity

As an expert developer well-versed in data quality best practices, data validation is an Excel feature…

How to Start a Podcast: The Ultimate Step-by-Step Guide for Developers

How to Start a Podcast: The Ultimate Step-by-Step Guide for Developers

Photo by Surface on Unsplash As a full-stack developer with over 10 years of experience building…

Unleash Your Coding Potential with a Chromebook

Unleash Your Coding Potential with a Chromebook

Chromebooks have come a long way since their inception over a decade ago. What started as…

How Developers Can Overcome Imposter Syndrome

How Developers Can Overcome Imposter Syndrome

Do you ever feel like a fraud programming alongside intensely skilled developers? When you build things…

An Introduction to Q-Learning: Reinforcement Learning from a Full-Stack Perspective

*Photo by [Franck V.](https://unsplash.com/@franckinjapan?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/robot-arm?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)* As a full-stack developer, I regularly apply machine learning techniques…

How to Track User Interactions in Your React App: A Complete Guide

How to Track User Interactions in Your React App: A Complete Guide

Understanding how users interact with your React application is critical. With robust analytics tracking, you gain…

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

Nathan Sebhastian

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:

NameOperation exampleMeaning
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Remainder assignment
Exponentiation assignment

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:

NameOperation exampleMeaning
Equal Returns if the operands are equal
Not equal Returns if the operands are not equal
Strict equal Returns if the operands are equal and have the same type
Strict not equal Returns if the operands are not equal, or have different types
Greater than Returns if the left operand is greater than the right operand
Greater than or equal Returns if the left operand is greater than or equal to the right operand
Less than Returns if the left operand is less than the right operand
Less than or equal Returns if the left operand is less than or equal to the right operand

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:

NameOperation exampleMeaning
Logical AND Returns if all operands are , else returns
Logical OR`xy`Returns if one of the operands is , else returns
Logical NOT Reverse the result: returns if and vice versa

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 .

beginning-js-cover

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!

Read more posts .

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

Comparison Operators in Programming

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

What is a Comparison Operator?

  • Common Comparison Operators
  • Equal to (==) Comparison Operator
  • Not equal to (!=) Comparison Operator
  • Greater than (>) Comparison Operator
  • Greater than or equal to (>=) Comparison Operator
  • Less than (<) Comparison Operator
  • Less than or equal to (<=) Comparison Operator

Comparison Operator is an operator that compares two operands and return true if the comparison evaluates to true otherwise, it returns false. They are important in programming, as they help us to compare values and expressions. The return value of a comparison is either true or false. 

Common Comparison Operators:

  • Equality Operator (==) .
  • Inequality Operator (!=)
  • Greater Than Operator (>)
  • Less Than Operator (<)
  • Greater Than or Equal To Operator (>=)
  • Less Than or Equal To Operator (<=)

Equal to (==) Comparison Operator:

The “equal to” (==) operator is a comparison operator widely used in programming languages to determine whether two values or expressions are equal .

Example of Equal to (==) Comparison Operator:

Here are the example of Equal to (==) Operator in different language:

Not equal to (!=) Comparison Operator:

The “not equal to” (!=) operator is a comparison operator used in programming languages to determine whether two values or expressions are not equal.

Example of Not equal to (!=) Comparison Operator:

Here are the example of Not equal to (!=) Operator in different language:

Greater than (>) Comparison Operator:

The “greater than” (>) operator is a comparison operator used in programming languages to determine whether the value or expression on the left of the operand is greater than the value or expression on the right.

Example of Greater than (>) Comparison Operator:

Here are the example of Greater than (>) Operator in different language:

Greater than or equal to (>=) Comparison Operator:

The “greater than or equal to” (>=) operator is a comparison operator used in programming languages to determine whether the value or expression on the left of the operand is greater than or equal to the value or expression on the right.

Example of Greater than or equal to (>=) Comparison Operator:

Here are the example of Greater than or equal to (>=) Operator in different language:

Less than (<) Comparison Operator:

The “less than” (<) operator is a comparison operator used in programming languages to determine whether the value or expression on the left of the operand is less than the value or expression on the right.

Example of Less than (<) Comparison Operator:

Here are the example of Less than (<) Operator in different language:

Less than or equal to (<=) Comparison Operator:

The “less than or equal to” (<=) operator is a comparison operator used in programming languages to determine whether the value or expression on the left of the operand is less than or equal to the value or expression on the right.

Example of Less than or equal to (<=) Comparison Operator:

Here are the example of Less than or equal to (<=) Operator in different language:

Conclusion:

Comparison operators are like tools that programmers use to compare things in their code. They help decide if something is true or false, which is super important for making decisions in programs. By knowing how to use these comparison operators properly, programmers can write code that works better and is easier to manage, no matter what kind of programming they’re doing.

Please Login to comment...

Similar reads.

  • Programming
  • Best 10 IPTV Service Providers in Germany
  • Python 3.13 Releases | Enhanced REPL for Developers
  • IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
  • Best SSL Certificate Providers in 2024 (Free & Paid)
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

Operator Description Usage Result
=== Strictly equal 2 === 2 true
!== Not strictly-equal 2 !== "2" true
== Equal (or "loosely equal") 2 == "2" true
!= Not equal 2 != "3" true
> Greater than 3 > 2 true
>= Greater than or equal to 2 >= 2 true
< Less than 2 < 3 true
<= Less than or equal to 2 <= 3 true

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.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

What alternatives are there for C/C++ assignment operator (=) and equality operators (==) syntax?

C/C++ use = for assignment and == for equality comparision. For example, a snippet in C++ can be like this:

But this can lead to unwanted bugs when programmers accidentally make a typo. Consider this example:

This is a (very) common typo in C/C++, partly because the two operators are so similar.

So what are the alternatives?

  • language-design

kaya3's user avatar

  • 4 $\begingroup$ Whatever syntax you choose for these, you can prevent this exact mistake by not having assignment expressions at all. nuclear_code = 1234; can be a statement without nuclear_code = 1234 needing to be allowed as an expression; Python did this before eventually relenting and adding the assignment operator := . Another issue that works against C in this regard is the coercion to boolean; in Java, if(nuclear_code = 1234) would be a type error because the condition must be a boolean , not an int . $\endgroup$ –  kaya3 Commented May 21, 2023 at 10:27
  • $\begingroup$ @kaya3 while that is true, the C/C++ way of doing it is a separate question in itself. I think that this still need to be asked. $\endgroup$ –  justANewbie Commented May 21, 2023 at 10:48
  • $\begingroup$ Yes, nothing wrong with the question. Just pointing out that there are more approaches to addressing this issue than just the choice of syntax for the two operators ─ and indeed, some languages use the same syntax = for both things because the context determines whether it's a name binding or an equality check. $\endgroup$ –  kaya3 Commented May 21, 2023 at 12:02
  • $\begingroup$ so are you asking particularly about design strategies to prevent these kinds of mistakes? Because I don't see that represented in your title, and if you are (asking about that), it should be (represented in your title) $\endgroup$ –  starball Commented May 21, 2023 at 19:03
  • 3 $\begingroup$ Not syntax, but in Swift assignment expressions are of type void, so this error can't happen either. $\endgroup$ –  chrysante Commented May 21, 2023 at 21:36

17 Answers 17

Just throw unicode symbols at it (the apl way).

APL uses ← for assignment and = / ≡ for equality ( = is term-wise, ≡ is for the whole array). If you can afford to just throw Unicode at the problem, sometimes it's a fun solution :) really depends on how the language is meant to be written, though.

RubenVerg's user avatar

  • 1 $\begingroup$ Not just Unicode have those symbols. Some calculators' BASIC dialects use ← as assignment too, from their limited character set. $\endgroup$ –  Longinus Commented May 22, 2023 at 1:52
  • 1 $\begingroup$ Some dialects of Smalltalk use _ for assignment, because early versions of ASCII had an arrow at that codepoint. $\endgroup$ –  Bbrk24 Commented May 22, 2023 at 4:16
  • $\begingroup$ @Longinus sure, but nowadays SBCS's are basically just Unicode mappings. I'd assume modern implementations of those BASIC's just read the (potentially sbcs-encoded) file and then display it as Unicode. $\endgroup$ –  RubenVerg Commented May 22, 2023 at 5:03
  • $\begingroup$ I can't really tell if this answer is serious. If it is, how do you expect users to type these symbols? $\endgroup$ –  chrysante Commented May 27, 2023 at 20:29
  • 1 $\begingroup$ @chrysante It is completely serious. In Dyalog APL, you'd hit your APL key (backtick by default) and then [ . $\endgroup$ –  RubenVerg Commented May 27, 2023 at 21:27

Distinguish Assignment and Equality by Context

Some languages use = for both assignment and equality. The way the language differentiates the two use cases is by constraining the grammar so it's obvious which context is meant.

For instance, in BASIC, there is no such thing as an "expression statement", so if you write something like x=1 on a line by itself, the only possible interpretation is that you are assigning 1 to x . The alternative interpretation of "check if x is equal to 1 and discard the result" isn't an allowed interpretation in the language. This is in contrast to a language like C where both interpretations are legal (and thus, the compiler needs an additional symbol to disambiguate the two interpretations). Some languages also use a keyword like let or set to begin an assignment statement which can also help distinguish the two.

The advantage of having only one operator for both operations is that it simplifies the language. It also means that the compiler will never misinterpret your program because of a careless error. On the other hand, it is less expressive than languages that separate out the two operations. For instance, in C++, you can assign to variables within a condition or loop. In a language like BASIC, you cannot do this which may lead to more verbose code in some cases.

Isaiah's user avatar

Even though the OP sepcifically asks for different syntax to prevent this kind of error, I would make the case that a better approach is a semantic solution:

The reason why this error can occur in C++ (and in C for that matter) is that an assignment expression evaluates to a reference to the assigned variable ( int& in this case) and that int is implicitly convertible to bool (*). By changing either of these properties we can prevent this error.

If we forbid implicit narrowing conversions or just the implicit int -> bool conversion we are already fine. This however prevents the following common C idiom:

But I would argue that this alternative code is easier to understand and just as simple to write:

If we evaluate assignment expressions not to a reference to the assigned value but to void we also solve the problem, but this time we prevent this idiom:

However this is rarely used and confusing if not seen before, and the alternative

is not significantly more verbose (and much clearer), so I would argue that losing this idiom is also not much of a loss if not an improvement.

So in conclusion I argue that while either of the approaches solves the problem, both of them are reasonable in their on right and can prevent other possible code smells.

Also now you are free to choose whatever syntax you like without the restriction of having to solve this problem.

(*) On top of that, in clauses of if statements, also explicit conversions to bool are considered in C++. This rule exists so class authors can make conversions to bool explicit, which prevents implicit conversions from the custom type to integral types (via class X -> bool -> int ) while still allowing the class to be used as a condition in if statements, but in our case it makes matters worse.

chrysante's user avatar

  • 1 $\begingroup$ An alternative is only forbidding raw assignment in a boolean context. Extra-parentheses are cheap enough. Also, if a , b and/or c are long and/or expressions with side-effects, the rewrite will be quite cumbersome and not actually that trivial. $\endgroup$ –  Deduplicator Commented Jul 3, 2023 at 15:44
  • $\begingroup$ @Deduplicator If a , b or c are complex expressions, you can store them to temporaries. That's what the compiler does under the hood if you write a nested assignment expression anyhow. I agree that forbidding raw assignment in if-conditions is also a solution, but that does not prevent the error in other boolean expressions. $\endgroup$ –  chrysante Commented Jul 3, 2023 at 16:38

The Pascal way

i.e using := for assignment and = for equality check.

The example in the question can be written in Pascal as:

This is so harder to mistype the two.

  • 2 $\begingroup$ Just as a note about this, := was chosen because it looked a bit like the left-arrow symbol in mathematics, ⟸, but wouldn't be confused for "less than or equal to". Prolog uses :- for a similar reason. $\endgroup$ –  Pseudonym Commented May 22, 2023 at 1:02
  • 5 $\begingroup$ @Pseudonym I believe the := symbol exists in mathematics as well, and has the meaning of introducing the definition for a new variable. The double arrows, on the other hand, I've never seen used for anything besides implication. Might be a case of poorly internationalized syntax, though) $\endgroup$ –  abel1502 Commented May 27, 2023 at 16:26
  • $\begingroup$ That's what I am doing in my programming language, AEC . $\endgroup$ –  FlatAssembler Commented Jul 10, 2023 at 18:47

The GNU solution to the if(x = y) {} problem is to require double parenthesisation where only if((x = y)) {} is unambiguous. That said, to mean assignment, the = , := , <- and ← operators are common across many languages descending from C, Pascal and BASIC. Vale uses a set keyword to mean reassignment.

In languages where the concept of "(re)assignment" does not exist, like most Functional and Logical ones, it is not uncommon to see = be used both for bindings and as the equality binary operator, along with == . For instance, in a language lacking builtin mutation support, this code is unambiguous:

Some English-oriented languages, like CoffeeScript , also use a is keyword.

For completeness, are also common as inequality operators != , /= , <> , ≠ and isnt , all used in various languages.

Longinus's user avatar

Common Lisp

Most of the time when you need a variable, you'll use let .

There's also setf .

Equality checking looks like one of the following (depending on what exactly you want—there are more equality operators).

It's really hard to accidentally mix the two up.

Aman Grewal's user avatar

Use : , like JSON

Assignment and comparison have different purposes, return values, and allowed syntactic locations. Therefore, they should be represented with bigger differences than a single extra character.

The use of : for "assignments" is already fairly common and should be familiar to users:

  • JSON/object notation: uses colon to bind a value to a key.
  • English: like this list, where a colon associates a value or comment with an entry.

This gives you a one-character solution for assignment, leaves = free for equality, and should be immediately clear to readers.

BoppreH's user avatar

  • $\begingroup$ : is used for assignment in K and Q. $\endgroup$ –  Adám Commented Oct 11, 2023 at 21:51

It partly depends on the semantics of variables and the semantics of equality.

Some languages distinguish between intensional and extensional equality . One example of this might be a set of integers represented as a binary search tree. Two sets are intensionally equal if the trees have the same structure, but extensionally equal if the numbers in the sets are the same.

Yet other languages have different notions of equality testing that depends on whether or not they will coerce types. Does 3 == 3.0 in a dynamically typed language? Sometimes you want that and sometimes you don't.

Other languages have object identity, which is different from equality.

This is a lot of symbols for equality testing that you might need to invent! Common Lisp has four of them.

Logic languages have only one symbol = , and it means unification . Just looking at simple values like numbers for the moment, if you type X = Y , then it can mean several things:

  • If X is a free variable but Y has a value already bound to it, this assigns that value to X .
  • Same thing if Y is free but X is bound; this is left-assignment.
  • If X and Y are both bound, then this is an equality test.
  • If X and Y are both free, then this aliases the two variables together. A subsequent binding of X will automagically also bind Y .

In general, X and Y could be data structures with some bound and some unbound variables inside it, in which case the full unification algorithm is run.

Pseudonym's user avatar

In Assembly ( mov ) or more basic languages there is a keyword for assignment, such as:

I am personally not a fan of this because I prefer punctuation as operators, but this is an option that resolves ambiguity.

Or in Assembly:

CPlus's user avatar

Different Spellings

Other common variations for assignment are := and (so far unmentioned) <- . JavaScript is notorious for having many different comparison operators.

Vale has the interesting variation that x = 42 is only a variable declaration, and assignment must be written set x = 42 . I find, like the author, that I also write many more dclarations than assignments.

Different Semantics

A functional language, using static single assignments, or one using linear types , allows assignment only within bindings, which can be marked with let . Alternatively, since newer languages tend to discourage mutability and assignments, you could mark assignments with set , or do both. Since is is no longer than == and be or to no longer than := or <- , this could be valid syntax:

Davislor's user avatar

Modern programming languages like Go use the "="/":=" for assignment and "==" for the comparison. It gives a compile time error if you mistype "=" instead of "==". Another suggestion would be to use constants when comparing, but that wouldn't solve your problem with mistyping in C++.

user514's user avatar

  • $\begingroup$ Welcome to PLDI. How does your answer differ from justANewbie's answer? $\endgroup$ –  Isaiah Commented May 21, 2023 at 16:03
  • $\begingroup$ @Isaiah Pascal uses = for equality comparison, and Go uses == for equality comparison. The point is that Go allows = instead of := for assignment when it's not in an expression. This is also the same as Python ─ = is assignment but not an expression, := is an assignment expression, == is an equality comparison. $\endgroup$ –  kaya3 Commented May 21, 2023 at 17:53
  • 4 $\begingroup$ "Modern programming languages like F# use = for both bindings and equality." It's a bold move to make a blanket statement like "modern PLs do x " when they disagree with each other on how to do x . $\endgroup$ –  Longinus Commented May 22, 2023 at 1:56

Coming relatively out of left field is Swift’s pattern-matching operator ~= . It’s rarely written in source, instead the result of desugaring a switch or if case statement, but you could use it instead of == for regular equality comparison if you wanted to.

Bbrk24's user avatar

The original Smalltalk uses ← for assignment and = for equality. It also uses ↑ for return.

The original Smalltalk developed at Xerox used its own workstation developed at Xerox with its own CPU developed at Xerox and its own input devices (keyboard and mouse) developed at Xerox. Smalltalk was its own Operating System as well.

All this to say that it also had its own character set and character encoding.

When Smalltalk first was ported to other systems using the ASCII character encoding, it turned out that ASCII had the character ^ at the same code point where Smalltalk had ↑ , so all Smalltalk was rendered with ^ for return on machines that used ASCII. It still looks like an upwards arrow, so it still kind of works.

Assignment was not so lucky, though: where Smalltalk had ← , ASCII has _ , so all assignments in Smalltalk were rendered as _ in ASCII. This was somewhat unsatisfactory, so it was decided to change the language specification use := for assignment. However, some Smalltalks still accept _ even today.

Jörg W Mittag's user avatar

  • $\begingroup$ I mentioned this in a comment on another answer, but this is much more thorough (as is expected from the nature of comments). $\endgroup$ –  Bbrk24 Commented Jul 6, 2023 at 17:05

Use ,= or ;=

We could already understand ,= as the += -like version of , in C-style operators. And ;= looks less confusing, if you already merge , with ; .

user23013's user avatar

Most compiler have the decency to give you a warning if you use the wrong operator, or if the compiler isn't sure. For example, with a good C compiler I expect that

gives a warning. And if I really want to store 1234 and then examine whether it is zero, these compilers may allow

which tells the compiler "be quiet, I know what I'm doing".

Newer languages don't allow integers to be used as boolean values. So the first example might not compile if the = operator doesn't yield a result, or it yields an integer result which cannot be used in an "if" statement. That's assuming that

would be very rare.

You could use different pairs of tokens. := and =, or = and .eq. like FORTRAN did, or a leftarrow for assignment. The warning, and possible changed semantics, is the simplest solution. In the end, if the code you type is not the code you wanted, that's your problem.

gnasher729's user avatar

You can raise an error

For example this code in Python is correct:

raise an error (no confusing bug like C++):

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged syntax language-design ..

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Why did the Fallschirmjäger have such terrible parachutes?
  • Background for the Elkies-Klagsbrun curve of rank 29
  • I would like to add 9 months onto a field table that is a date and have it populate with the forecast date 9 months later
  • Dutch Public Transportation Electronic Payment Options
  • Parse Minecraft's VarInt
  • What is opinion?
  • How can judicial independence be jeopardised by politicians' criticism?
  • How can moral disagreements be resolved when the conflicting parties are guided by fundamentally different value systems?
  • Which version of Netscape is this, on which OS?
  • I overstayed 90 days in Switzerland. I have EU residency and never got any stamps in passport. Can I exit/enter at airport without trouble?
  • Image Intelligence concerning alien structures on the moon
  • The answer is not wrong
  • What's the average distance traveled on a typical single engine aircraft?
  • Where to donate foreign-language academic books?
  • Why is Legion helping you whilst geth are fighting you?
  • How does the summoned monster know who is my enemy?
  • I am a sailor. I am planning to call my family onboard with me on the ship from the suez
  • Do the amplitude and frequency of gravitational waves emitted by binary stars change as the stars get closer together?
  • The size of elementary particles
  • What is the difference between a "Complaint for Civil Protection Order" and a "Motion for Civil Protection Order"?
  • Cannot open and HTML file stored on RAM-disk with a browser
  • What are some refutations to the etymological fallacy?
  • How is it possible to know a proposed perpetual motion machine won't work without even looking at it?
  • What is the name of this simulator

the assignment operator and the comparison operator are the same

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

Comparison operators are used to compare two values:

Operator Name Example Try it
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

cppreference.com

Comparison operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
- block
  
(C++11)
(C++11)
(C++11)
/
(C++11)
    
(C++11)
expression
pointer
specifier
specifier (C++11)
specifier (C++11)
(C++11)
(C++11)
(C++11)
(C++11)
General
(lvalue, rvalue, xvalue)
(sequence points)
(C++11)
Literals
including
(C++11)
(C++11)
Operators
:
:  
:
:
:
:
:
, , , , , , , , , ,
, , ,
, , , , , , , , , , , ,
, ,
, , , , , , (C++20)
, , , , , ,
, ,

Compares the arguments.

Operator name    Syntax    Prototype examples (for class T)
As member function As free (namespace) function
equal to Yes bool T::operator ==(const T2 &b) const; bool operator ==(const T &a, const T2 &b);
not equal to Yes bool T::operator !=(const T2 &b) const; bool operator !=(const T &a, const T2 &b);
less than Yes bool T::operator <(const T2 &b) const; bool operator <(const T &a, const T2 &b);
greater than Yes bool T::operator >(const T2 &b) const; bool operator >(const T &a, const T2 &b);
less than or equal to Yes bool T::operator <=(const T2 &b) const; bool operator <=(const T &a, const T2 &b);
greater than or equal to Yes bool T::operator >=(const T2 &b) const; bool operator >=(const T &a, const T2 &b);
three-way comparison (C++20) Yes /*R*/ T::operator <=>(const T2 &b) const; /*R*/ operator <=>(const T &a, const T2 &b);

, most also return bool so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including . is the return type of operator <=> ( ).
Two-way comparison Arithmetic comparison operators Example Pointer comparison operators Example Notes Three-way comparison Example Notes Standard library Defect reports See also

[ edit ] Two-way comparison

The two-way comparison operator expressions have the form

lhs rhs (1)
lhs rhs (2)
lhs rhs (3)
lhs rhs (4)
lhs rhs (5)
lhs rhs (6)

In all cases, for the built-in operators, lhs and rhs must have either

  • arithmetic or enumeration type (see arithmetic comparison operators below)
  • pointer type (see pointer comparison operators below)

after the application of the lvalue-to-rvalue , array-to-pointer and function-to-pointer standard conversions. The comparison is deprecated if both operands have array type prior to the application of these conversions. (since C++20)

In any case, the result is a bool prvalue.

[ edit ] Arithmetic comparison operators

If the operands have arithmetic or enumeration type (scoped or unscoped), usual arithmetic conversions are performed on both operands following the rules for arithmetic operators . The values are compared after conversions:

[ edit ] Example

[ edit ] pointer comparison operators.

Comparison operators can be used to compare two pointers.

Only equality operators ( operator == and operator ! = ) can be used to compare the following pointer pairs:

  • two pointers-to-members
  • a null pointer constant with a pointer or a pointer-to-member
value with a null pointer constant (which can also be a value) (since C++11)

First, pointer conversions (pointer to member conversions if the arguments are pointers to members) , function pointer conversions, (since C++17) and qualification conversions are applied to both operands to obtain the composite pointer type , as follows

If both operands are null pointer constants, the composite pointer type is (since C++11)
  • a pointer to cv1 void , and
  • a pointer to cv2 T , where T is an object type or void ,
  • P1 , a pointer to (possibly cv-qualified) T1 , and
  • P2 , a pointer to (possibly cv-qualified) T2 ,
  • MP1 , pointer to member of T1 of type (possibly cv-qualified) U1 , and
  • MP2 , pointer to member of T2 of type (possibly cv-qualified) U2 ,

In the definition above, cv-combined type of two pointer types P1 and P2 is a type P3 that has the same number of levels and type at every level as P1 , except that cv-qualifications at every level are set as follows:

For example, the composite pointer type of void * and const int * is const void * . The composite pointer type of int ** and const int ** is const int * const * . Note that until resolution of CWG1512 , int ** and const int ** could not be compared.

In addition to the above, the composite pointer type between pointer to function and pointer to noexcept function (as long as the function type is the same) is pointer to function.

(since C++17)

Note that this implies that any pointer can be compared with void * .

The result of comparing two pointers to objects (after conversions) is defined as follows:

The result of equality comparison of two pointers (after conversions) is defined as follows:

The result of comparing two pointers to members (after conversions) is defined as follows:

If a pointer p compare equal to pointer q , p <= q and p >= q both yield true and p < q and p > q both yield false .

If a pointer p compares greater than a pointer q , then p >= q , p > q , q <= p , and q < p all yield true and p <= q , p < q , q >= p , and q > p all yield false .

If two pointers are not specified to compare greater or compare equal, the result of the comparison is unspecified. An unspecified result may be nondeterministic, and need not be consistent even for multiple evaluations of the same expression with the same operands in the same execution of the program:

In overload resolution against user-defined operators , for every pair of promoted arithmetic types L and R , including enumeration types, the following function signatures participate in overload resolution:

operator<(L, R);
operator>(L, R);
operator<=(L, R);
operator>=(L, R);
operator==(L, R);
operator!=(L, R);

For every type P which is either pointer to object or pointer to function, the following function signatures participate in overload resolution:

operator<(P, P);
operator>(P, P);
operator<=(P, P);
operator>=(P, P);
operator==(P, P);
operator!=(P, P);

For every type MP that is a pointer to member object or pointer to member function or std::nullptr_t , the following function signatures participate in overload resolution:

operator==(MP, MP);
operator!=(MP, MP);

[ edit ] Notes

Because these operators group left-to-right, the expression a < b < c is parsed ( a < b ) < c , and not a < ( b < c ) or ( a < b ) && ( b < c ) .

A common requirement for user-defined operator< is strict weak ordering . In particular, this is required by the standard algorithms and containers that work with Compare types: std::sort , std::max_element , std::map , etc.

Although the results of comparing pointers of random origin (e.g. not all pointing to members of the same array) is unspecified, many implementations provide strict total ordering of pointers, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of std::less for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as std::set or std::map .

For the types that are both EqualityComparable and LessThanComparable , the C++ standard library makes a distinction between equality , which is the value of the expression a == b and equivalence , which is the value of the expression ! ( a < b ) && ! ( b < a ) .

Comparison between pointers and null pointer constants was removed by the resolution of CWG issue 583 included in N3624

The three-way comparison operator expressions have the form

a b

The expression returns an object such that

  • ( a <=> b ) < 0 if a < b
  • ( a <=> b ) > 0 if a > b
  • ( a <=> b ) == 0 if a and b are equal/equivalent.

If one of the operands is of type bool and the other is not, the program is ill-formed.

If both operands have arithmetic types, or if one operand has unscoped enumeration type and the other has integral type, the usual arithmetic conversions are applied to the operands, and then

  • If a narrowing conversion is required, other than from an integral type to a floating point type, the program is ill-formed.
  • Otherwise, if the operands have integral type, the operator yields a prvalue of type std::strong_ordering :
  • std::strong_ordering::equal if both operands are arithmetically equal,
  • std::strong_ordering::less if the first operand is arithmetically less than the second
  • std::strong_ordering::greater otherwise.
  • Otherwise, the operands have floating-point type, and the operator yields a prvalue of type std::partial_ordering . The expression a <=> b yields
  • std::partial_ordering::less if a is less than b
  • std::partial_ordering::greater if a is greater than b
  • std::partial_ordering::equivalent if a is equivalent to b ( - 0 <=> + 0 is equivalent)
  • std::partial_ordering::unordered ( NaN <=> anything is unordered).

If both operands have the same enumeration type E , the operator yields the result of converting the operands to the underlying type of E and applying <=> to the converted operands.

If at least one of the operands is a pointer or pointer-to-member, array-to-pointer conversions, derived-to-base pointer conversions, function pointer conversions, and qualification conversions are applied as necessary to convert both operands to the same pointer type, and the resulting pointer type is an object pointer type, p <=> q returns a prvalue of type std::strong_ordering :

  • std::strong_ordering::equal if p == q ,
  • std::strong_ordering::less if p < q ,
  • std::strong_ordering::greater if p > q .
  • unspecified result if comparison is unspecified for these pointer values (such as when they do not point into the same object or array).

Otherwise, the program is ill-formed.

In overload resolution against user-defined operators , for pointer or enumeration type T , the following function signature participates in overload resolution:

(T, T);

Where R is the ordering category type defined above.

Three-way comparison can be automatically generated for class types, see default comparisons .

If both of the operands are arrays, three-way comparison is ill-formed.

macro Value Std Comment
201907L (C++20) Three-way comparison (compiler support)
201907L (C++20) Three-way comparison (library support); adding three-way comparison to the library

[ edit ] Standard library

Comparison operators are overloaded for many classes in the standard library.

operator!= (removed in C++20) checks whether the objects refer to the same type
(public member function of )
operator!=operator<operator<=> (removed in C++20)(removed in C++20)(C++20) compares two s
(function)
operator!=operator<operator<=> (removed in C++20)(removed in C++20)(C++20) compares s and s
(function)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the pair
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the tuple
(function template)
operator!= (removed in C++20) compares the contents
(public member function of )
operator!= (removed in C++20) compares two allocator instances
(public member function of )
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(C++20) compares to another or with nullptr
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) compares with another or with nullptr
(function template)
operator!= (removed in C++20) compares a with nullptr
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) compares two durations
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) compares two time points
(function template)
operator!= (removed in C++20) compares two scoped_allocator_adaptor instances
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(C++20) compares the underlying objects
(public member function of )
operator!=operator<operator>operator<=operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares two strings
(function template)
operator!= (removed in C++20) equality comparison between locale objects
(public member function of )
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the array
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the deque
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the forward_list
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the list
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the vector
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the map
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the multimap
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the set
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) lexicographically compares the values in the multiset
(function template)
operator!= (removed in C++20) compares the values in the unordered_map
(function template)
operator!= (removed in C++20) compares the values in the unordered_multimap
(function template)
operator!= (removed in C++20) compares the values in the unordered_set
(function template)
operator!= (removed in C++20) compares the values in the unordered_multiset
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++20) lexicographically compares the values in the queue
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++20) lexicographically compares the values in the stack
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++20) compares the underlying iterators
(function template)
operator!=operator<operator<=operator>operator>=operator<=> (C++11)(removed in C++20)(C++11)(C++11)(C++11)(C++11)(C++20) compares the underlying iterators
(function template)
operator!= (removed in C++20) compares two s
(function template)
operator!= (removed in C++20) compares two s
(function template)
operator!= (removed in C++20) compares two complex numbers or a complex and a scalar
(function template)
operator!=operator<operator<=operator>operator>= compares two valarrays or a valarray with a value
(function template)
operator!= (C++11)(removed in C++20) compares the internal states of two pseudo-random number engines
(function)
operator!= (C++11)(removed in C++20) compares two distribution objects
(function)
operator!=operator<operator<=operator>operator>=operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) compares a with another , a string, or a character
(function template)
operator!= (removed in C++20) lexicographically compares the values in the two match result
(function template)
operator!= (removed in C++20) compares two s
(public member function of )
operator!= (removed in C++20) compares two s
(public member function of )
operator!=operator< operator<= operator> operator>= operator<=> (removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(removed in C++20)(C++20) compares two objects
(function)

The namespace std::rel_ops provides generic operators ! = , > , <= , and >= :

operator>operator<=operator>= automatically generates comparison operators based on user-defined operator== and operator<
(function template)

[ edit ] Defect reports

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

DR Applied to Behavior as published Correct behavior
C++98 all six comparison operators could be used to
compare a pointer with a null pointer constant
only equality operators allowed
C++98 the actual semantics of arithmetic comparisons (e.g.
whether 1 < 2 yields or ) were unspecified
specification added
C++98 pointers to function types and pointers
to void did not have built-in comparisons
added comparison specification
for these pointers
C++98 the rule of composite pointer type was incomplete, and thus
did not allow comparison between int** and const int**
made complete
C++98 non-array objects were considered to belong to arrays with
one element only for the purpose of pointer arithmetic
the rule is also
applied to comparison
C++98 two pointers to members of classes that are different and
neither is the base class of the other did not compare equal
even if the offsets of the pointed members can be the same
the result is
unspecified
in this case
C++98 it was not clear whether two pointers to members
that refer to different members of the same union
compare equal as if they refer to the same member
they compare
equal in this case
C++98 a pointer to non-array object was only treated as a
pointer to the first element of an array with size 1
in pointer comparison if the pointer is obtained by &
applies to all pointers
to non-array objects

[ edit ] See also

  • Operator precedence
  • Operator overloading
  • Compare (named requirements)
Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Comparison operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 12 October 2022, at 01:25.
  • This page has been accessed 932,026 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Multiple Comparison / Assignment Operators on the Same Line in JavaScript

In the above, what is the line inside of the function doing and how does it work?

Lloyd Banks's user avatar

2 Answers 2

First it's doing the comparison input != 1 , and then assigning the result of that (which will be true or false ) the variable value . The != is a comparison , the = is an assignment .

This is exactly the same as any other assignment: The right-hand side is evaluated, and assigned to the left-hand side.

T.J. Crowder's user avatar

See Operator Precedence .

!= has a precedence of 9 and = has a precedence of 17.

Therefore it evaluates input != 1 and then assigns the result to value .

Quentin's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • How would you say a couple of letters (as in mail) if they're not necessarily letters?
  • How to logging Preferences library
  • What are some refutations to the etymological fallacy?
  • How can moral disagreements be resolved when the conflicting parties are guided by fundamentally different value systems?
  • Has the US said why electing judges is bad in Mexico but good in the US?
  • What prevents a browser from saving and tracking passwords entered to a site?
  • Regression techniques for a “triangular” scatterplot
  • Has a tire ever exploded inside the Wheel Well?
  • My supervisor wants me to switch to another software/programming language that I am not proficient in. What to do?
  • How can I prove the existence of multiplicative inverses for the complex number system
  • Is it possible to accurately describe something without describing the rest of the universe?
  • I am a sailor. I am planning to call my family onboard with me on the ship from the suez
  • How to export a list of Datasets in separate sheets in XLSX?
  • How to reply to reviewers who ask for more work by responding that the paper is complete as it stands?
  • What's the average distance traveled on a typical single engine aircraft?
  • Why there is no article after 'by'?
  • Book or novel about an intelligent monolith from space that crashes into a mountain
  • Trying to install MediaInfo Python 3.13 (Ubuntu) and it is not working out as expected
  • Is there a difference between these two layouts?
  • What happens if all nine Supreme Justices recuse themselves?
  • I would like to add 9 months onto a field table that is a date and have it populate with the forecast date 9 months later
  • Why did the Fallschirmjäger have such terrible parachutes?
  • What to do when 2 light switches are too far apart for the light switch cover plate?
  • Who was the "Dutch author", "Bumstone Bumstone"?

the assignment operator and the comparison operator are the same

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Booleans

  • JavaScript Object.is()

JavaScript Ternary Operator

JavaScript null and undefined

  • JavaScript typeof Operator

JavaScript Comparison and Logical Operators

  • JavaScript Comparison Operators

Comparison operators compare two values and return a boolean value ( true or false ). For example,

Here, we have used the > comparison operator to check whether a (whose value is 3 ) is greater than b (whose value is 2 ).

Since 3 is greater than 2 , we get true as output.

Note: In the above example, a > b is called a boolean expression since evaluating it results in a boolean value.

Commonly Used Comparison Operators

Operator Meaning Example
Equal to
Not equal to
Strictly equal to
Strictly not equal to
Greater than
Less than
Greater than or equal to
Less than or equal to

1. JavaScript Equal To Operator

The equal to operator == evaluates to

  • true if the values of the operands are equal.
  • false if the values of the operands are not equal.

For example,

Note : In JavaScript, == is a comparison operator, whereas = is an assignment operator. If you mistakenly use = instead of == , you might get unexpected results.

2. Not Equal To Operator

The not equal to operator != evaluates to

  • true if the values of the operands aren't equal.
  • false if the values of the operands are equal.

3. Strict Equal To Operator

The strict equal to operator === evaluates to

  • true if both the values and the types of the operands are the same.
  • false if either the values or the types of the operands are not the same.

The == (equality) operator only checks the values of the operands and not their types. For example,

However, the === (strict equality) operator checks both the values and types of the operands. For example,

This means, the == operator returns true as long as the values of the operands are equal. But, the === operator only returns true when both the values and the types of the operands are equal.

4. Strict Not Equal To Operator

The strict not equal to operator !== evaluates to

  • true if either the values or the types of the operands are not the same.
  • false if both the values and the types of the operands are the same.

5. Greater Than Operator

The greater than operator > returns

  • true if the value on the left is greater than the value on the right.
  • false if the value on the left isn't greater than the value on the right.

6. Greater Than Or Equal To Operator

The greater than or equal to operator >= returns

  • true if the value on the left is greater than or equal to the value on the right.
  • false if the value on the left is less than the value on the right.

7. Less Than Operator

The less than operator < returns

  • true if the value on the left is less than the value on the right.
  • false if the value on the left isn't less than the value on the right.

8. Less Than Or Equal To Operator

The less than or equal to operator <= returns

  • true if the value on the left is less than or equal to the value on the right.
  • false if the value on the left is greater than the value on the right.
  • JavaScript Logical Operators

Logical operators return a boolean value by evaluating boolean expressions. For example,

Here, && is the logical operator AND . Since both the boolean expressions x < 6 and y < 5 are true , evaluating them with the && operator also results in true .

Commonly Used Logical Operators

Operator Syntax Description
(Logical AND) only if both and are
(Logical OR) if either or is
(Logical NOT) if is and vice versa

1. Logical AND Operator

The logical AND operator && returns true if both the expressions are true . For example,

  • (x < 4) && (4 >= x) results in true because both expressions are true .
  • (x <= 4) && (2 == 4) results in false because the expression 2 == 4 is false .
  • (x > 4) && (x == 4) results in false because both expressions are false .

2. Logical OR Operator

The logical OR operator || returns true if at least one expression is true . For example,

  • (x < 4) || (4 >= x) results in true because both expressions are true .
  • (x <= 4) || (2 == 4) results in true because the expression x <= 4 is true .
  • (x > 4) || (x == 4) results in false because both expressions are false .

3. Logical NOT Operator

The logical NOT operator ! returns true if the specified expression is false and vice versa. For example,

  • !true results in false because ! inverts the value of true to false .
  • !false results in true because ! inverts the value of false to true .
  • !(2 < 3) results in false because ! inverts the true value of (2 < 3) to false .

Frequently Asked Question

In JavaScript, we use comparison operators to compare two values and find the resulting boolean value ( true or false ). For example,

In the above example, we used the < operator to find the boolean value for the condition 4 < 5 .

On the other hand, we use logical operators to perform logical operations on boolean expressions. For example,

Here, the expression 4 < 5 gives us the boolean value true . The ! operator then acts on this boolean value and inverts it to false .

  • JavaScript if...else Statement

Table of Contents

  • JavaScript Equal To Operator
  • Strict Equal To Operator
  • Greater Than Operator
  • Less Than Operator
  • Logical AND Operator
  • Logical OR Operator
  • Logical NOT Operator

Video: JavaScript Comparison and Logical Operators

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

IMAGES

  1. Chapter 3: Selection Structures: Making Decisions

    the assignment operator and the comparison operator are the same

  2. Relational Operators.

    the assignment operator and the comparison operator are the same

  3. Assignment Operator Vs Comparison Operator

    the assignment operator and the comparison operator are the same

  4. Assignment Operators in C

    the assignment operator and the comparison operator are the same

  5. Assignment Operator Vs. Comparison Operator Using The Equal Sign

    the assignment operator and the comparison operator are the same

  6. Chapter 3 Edited by JJ Shepherd

    the assignment operator and the comparison operator are the same

VIDEO

  1. Assignment Operator & Comparison Operator in Javascript

  2. Operators in C language

  3. 3 Operators in PHP

  4. #phonk javascript in Assignment operator

  5. 28- Assignment and Compound assignment operators (Arabic)

  6. Assignment Operators in C Programming

COMMENTS

  1. What is the difference between = (Assignment) and == (Equal to) operators

    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.

  2. Assignment Operators in Programming

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

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

  4. Assignment Operators In C++

    The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a

  5. javascript

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

  6. The differences' between the operator "==" and

    In python and other languages like C, "=" is a assignment operator and is used to assign a value to a variable. Example: a=2 # the value of a is 2. whereas "==" is Comparison operator and is used to check whether 2 expressions give the same value .Equality check returns true if it succeeds and else return false. Example: a=2 b=3 c=2.

  7. Assignment operators

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

  8. What are comparisons and assignments?

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

  9. Operators

    The assignment operator (operator =, with one equal sign) is not the same as the equality comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-hand to the variable on its left, while the other (==) compares whether the values on both sides of the operator are equal.

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

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

  11. Learn JavaScript Operators

    Here is full list of all assignment operators: While very useful, misuse of assignment operators accounts for 5% of all JavaScript bugs as per research by Commission Junction. So take care when using them. Now we move on to comparison operators… Comparison Operators. Comparison operators are used to evaluate conditions by comparing operands ...

  12. Learn JavaScript 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: let x = 5; After the basic assignment operator, there are 5 more ...

  13. C++ Operator Precedence

    Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression a = b = c is parsed as a =(b = c), and not as (a = b)= c because of right-to-left associativity of assignment, but a + b - c is parsed (a + b)- c and not a +(b - c) because of left-to-right associativity of ...

  14. Python Operators (With Examples)

    3. Python Comparison Operators. Comparison operators compare two values/variables and return a boolean result: True or False. For example, a = 5 b = 2 print (a > b) # True. Here, the > comparison operator is used to compare whether a is greater than b or not.

  15. Comparison Operators in Programming

    Comparison Operator is an operator that compares two operands and return true if the comparison evaluates to true otherwise, it returns false. They are important in programming, as they help us to compare values and expressions. ... Assignment operators in programming are symbols used to assign values to variables. They offer shorthand ...

  16. Assignment operators

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

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

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

    JavaScript is notorious for having many different comparison operators. Vale has the interesting variation that x = 42 is only a variable declaration, and assignment must be written set x = 42. I find, like the author, that I also write many more dclarations than assignments. ... This is also the same as Python ─ = is assignment but not an ...

  19. Python Comparison Operators

    Python Comparison Operators. Comparison operators are used to compare two values: Operator Name Example ... x <= y: Try it » Related Pages. Python Operators Tutorial Operators Arithmetic Operators Assignment Operators Logical Operators Identity Operators Membership Operators Bitwise Operators

  20. Comparison operators

    Comparison operators. Compares the arguments. Where built-in operators return bool, most user-defined overloads also return bool so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void ). T2 can be any type including T .

  21. Multiple Comparison / Assignment Operators on the Same Line in

    4. First it's doing the comparison input != 1, and then assigning the result of that (which will be true or false) the variable value. The != is a comparison, the = is an assignment. This is exactly the same as any other assignment: The right-hand side is evaluated, and assigned to the left-hand side. answered Dec 18, 2013 at 22:40. T.J. Crowder.

  22. JavaScript Comparison and Logical Operators

    Comparison operators compare two values and return a boolean value ( true or false ). For example, const a = 3, b = 2; console.log(a > b); // Output: true. Run Code. Here, we have used the > comparison operator to check whether a (whose value is 3) is greater than b (whose value is 2 ). Since 3 is greater than 2, we get true as output.

  23. Comparison operators

    The type of any equality operator expression is int, and its value (which is not an lvalue) is 1 when the specified relationship holds true and 0 when the specified relationship does not hold.. if both operands have arithmetic types, usual arithmetic conversions are performed and the resulting values are compared in the usual mathematical sense (except that positive and negative zeroes compare ...