JS Tutorial

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

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

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

JavaScript Assignment

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

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

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

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation ( )
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

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

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

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

Note that strings are compared alphabetically:

JavaScript String Addition

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

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

The result of text1 will be:

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

Adding Strings and Numbers

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

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

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

JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

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

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001  1
| OR 5 | 1 0101 | 0001 0101  5
~ NOT ~ 5  ~0101 1010  10
^ XOR 5 ^ 1 0101 ^ 0001 0100  4
<< left shift 5 << 1 0101 << 1 1010  10
>> right shift 5 >> 1 0101 >> 1 0010   2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010   2

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

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

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

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

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

Left-hand-side expressions

« Previous Next »

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

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

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

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

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

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

For example, 3+4 or x*y .

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

For example, x++ or ++x .

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

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

Compound assignment operators
Name Shorthand operator Meaning

Destructuring

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

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

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

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

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

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

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to convert the operand to a number, if it is not already. returns .
returns
( ) Calculates the to the  power, that is, returns .
returns .

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

The following table summarizes JavaScript's bitwise operators.

Bitwise operators
Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same.
[Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

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

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

Bitwise operator examples
Expression Result Binary Description

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

Bitwise shift operators

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

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

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

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

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand can be converted to ; otherwise, returns .

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

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

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

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

Short-circuit evaluation

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

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

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

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

For example,

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

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

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

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

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

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

A unary operation is an operation with only one operand.

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

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

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

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

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

Deleting array elements

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

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

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

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

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

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

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

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

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

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

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

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

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

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

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

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

Relational operators

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

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

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

The following examples show some uses of the in operator.

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

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

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

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

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

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

Operator precedence
Operator type Individual operators
member
call / create instance
negation/increment
multiply/divide
addition/subtraction
bitwise shift
relational
equality
bitwise-and
bitwise-xor
bitwise-or
logical-and
logical-or
conditional
assignment
comma

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

  • Expressions

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

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

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

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

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

Primary expressions

Basic keywords and general expressions in JavaScript.

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

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

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

  • Grouping operator

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

Comprehensions

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

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

Left values are the destination of an assignment.

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

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

Spread operator

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

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

Similarly, the spread operator works with function calls:

Document Tags and Contributors

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

TekTutorialsHub-Logo

Assignment Operators in JavaScript

An assignment operator requires two operands. The value of the right operand is assigned to the left operand. The sign = denotes the simple assignment operator. JavaScript also has several compound assignment operators, which is actually shorthand for other operators. A list of all such operators are listed below.

Table of Contents

List of Assignment operators

Simple assignement operator, compound assignment operators.

NameSyntaxMeaning
Assignmentx = yx = y
Addition assignmentx += yx =x+ y
Subtraction assignmentx -= yx = x - y
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Exponentiation assignmentx **= yx = x ** y
Left shift assignmentx
Right shift assignmentx >>= yx = x >> y
Unsigned right shift assignmentx >>>= yx = x >>> y
Bitwise AND assignmentx &= yx = x & y
Bitwise XOR assignmentx ^= yx = x ^ y
Bitwise OR assignmentx |= yx = x | y
Logical AND assignmentx &&= yx && (x = y)
Logical OR assignmentx ||= yx || (x = y)
Logical nullish assignmentx ??= yx ?? (x = y)

An  =  assignment operator assigns the value of the right-hand operand to the left-hand variable.

x = 25; y = 25*100; z = x+y;

All operators except = listed in the table above are compound assignment operators. They are actually shorthand notations

For Examples

The Addition assignment += operator adds a value to a variable.

x = 25;   +=25;   //50;

is actually shorthand for

x= 25; = x + 25;    //50
  • Expressions & Operators
  • Precedency & Associativity
  • JavaScript Tutorial
  • JavaScript Operators
  • Arithmetic Operators
  • Unary plus (+) & Unary minus (-)
  • Increment & Decrement Operators
  • Comparison or Relational Operators
  • Strict Equality & Loose Equality Checker
  • Ternary Conditional Operator
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Nullish Coalescing Operator
  • Comma Operator
  • Operator Precedence

Related Posts

Introduction to JavaScript

Introduction to Javascript

Hello World in JavaScript

JavaScript Hello World Example

Leave a comment cancel reply.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed .

JavaScript Assignment Operators

JavaScript Assignment OperatorsExampleExplanation
=x = 15Value 15 is assigned to x
+=x += 15This is same as x = x + 15
-=x -= 15This is same as x = x – 15
*=x *= 15This is same as x = x * 15
/=x /= 15This is same as x = x / 15
%=x %= 15This is same as x = x % 15

JavaScript Assignment Operators Example

Javascript assignment operators example 2.

Javascript Tutorial

  • Javascript Basics Tutorial
  • Javascript - Home
  • JavaScript - Overview
  • JavaScript - Features
  • JavaScript - Enabling
  • JavaScript - Placement
  • JavaScript - Syntax
  • JavaScript - Hello World
  • JavaScript - Console.log()
  • JavaScript - Comments
  • JavaScript - Variables
  • JavaScript - let Statement
  • JavaScript - Constants
  • JavaScript - Data Types
  • JavaScript - Type Conversions
  • JavaScript - Strict Mode
  • JavaScript - Reserved Keywords
  • JavaScript Operators
  • JavaScript - Operators
  • JavaScript - Arithmetic Operators
  • JavaScript - Comparison Operators
  • JavaScript - Logical Operators
  • JavaScript - Bitwise Operators

JavaScript - Assignment Operators

  • JavaScript - Conditional Operators
  • JavaScript - typeof Operator
  • JavaScript - Nullish Coalescing Operator
  • JavaScript - Delete Operator
  • JavaScript - Comma Operator
  • JavaScript - Grouping Operator
  • JavaScript - Yield Operator
  • JavaScript - Spread Operator
  • JavaScript - Exponentiation Operator
  • JavaScript - Operator Precedence
  • JavaScript Control Flow
  • JavaScript - If...Else
  • JavaScript - While Loop
  • JavaScript - For Loop
  • JavaScript - For...in
  • Javascript - For...of
  • JavaScript - Loop Control
  • JavaScript - Break Statement
  • JavaScript - Continue Statement
  • JavaScript - Switch Case
  • JavaScript - User Defined Iterators
  • JavaScript Functions
  • JavaScript - Functions
  • JavaScript - Function Expressions
  • JavaScript - Function Parameters
  • JavaScript - Default Parameters
  • JavaScript - Function() Constructor
  • JavaScript - Function Hoisting
  • JavaScript - Self-Invoking Functions
  • JavaScript - Arrow Functions
  • JavaScript - Function Invocation
  • JavaScript - Function call()
  • JavaScript - Function apply()
  • JavaScript - Function bind()
  • JavaScript - Closures
  • JavaScript - Variable Scope
  • JavaScript - Global Variables
  • JavaScript - Smart Function Parameters
  • JavaScript Objects
  • JavaScript - Number
  • JavaScript - Boolean
  • JavaScript - Strings
  • JavaScript - Arrays
  • JavaScript - Date
  • JavaScript - Math
  • JavaScript - RegExp
  • JavaScript - Symbol
  • JavaScript - Sets
  • JavaScript - WeakSet
  • JavaScript - Maps
  • JavaScript - WeakMap
  • JavaScript - Iterables
  • JavaScript - Reflect
  • JavaScript - TypedArray
  • JavaScript - Template Literals
  • JavaScript - Tagged Templates
  • Object Oriented JavaScript
  • JavaScript - Objects
  • JavaScript - Classes
  • JavaScript - Object Properties
  • JavaScript - Object Methods
  • JavaScript - Static Methods
  • JavaScript - Display Objects
  • JavaScript - Object Accessors
  • JavaScript - Object Constructors
  • JavaScript - Native Prototypes
  • JavaScript - ES5 Object Methods
  • JavaScript - Encapsulation
  • JavaScript - Inheritance
  • JavaScript - Abstraction
  • JavaScript - Polymorphism
  • JavaScript - Destructuring Assignment
  • JavaScript - Object Destructuring
  • JavaScript - Array Destructuring
  • JavaScript - Nested Destructuring
  • JavaScript - Optional Chaining
  • JavaScript - Garbage Collection
  • JavaScript - Global Object
  • JavaScript - Mixins
  • JavaScript - Proxies
  • JavaScript Versions
  • JavaScript - History
  • JavaScript - Versions
  • JavaScript - ES5
  • JavaScript - ES6
  • ECMAScript 2016
  • ECMAScript 2017
  • ECMAScript 2018
  • ECMAScript 2019
  • ECMAScript 2020
  • ECMAScript 2021
  • ECMAScript 2022
  • ECMAScript 2023
  • JavaScript Cookies
  • JavaScript - Cookies
  • JavaScript - Cookie Attributes
  • JavaScript - Deleting Cookies
  • JavaScript Browser BOM
  • JavaScript - Browser Object Model
  • JavaScript - Window Object
  • JavaScript - Document Object
  • JavaScript - Screen Object
  • JavaScript - History Object
  • JavaScript - Navigator Object
  • JavaScript - Location Object
  • JavaScript - Console Object
  • JavaScript Web APIs
  • JavaScript - Web API
  • JavaScript - History API
  • JavaScript - Storage API
  • JavaScript - Forms API
  • JavaScript - Worker API
  • JavaScript - Fetch API
  • JavaScript - Geolocation API
  • JavaScript Events
  • JavaScript - Events
  • JavaScript - DOM Events
  • JavaScript - addEventListener()
  • JavaScript - Mouse Events
  • JavaScript - Keyboard Events
  • JavaScript - Form Events
  • JavaScript - Window/Document Events
  • JavaScript - Event Delegation
  • JavaScript - Event Bubbling
  • JavaScript - Event Capturing
  • JavaScript - Custom Events
  • JavaScript Error Handling
  • JavaScript - Error Handling
  • JavaScript - try...catch
  • JavaScript - Debugging
  • JavaScript - Custom Errors
  • JavaScript - Extending Errors
  • JavaScript Important Keywords
  • JavaScript - this Keyword
  • JavaScript - void Keyword
  • JavaScript - new Keyword
  • JavaScript - var Keyword
  • JavaScript HTML DOM
  • JavaScript - HTML DOM
  • JavaScript - DOM Methods
  • JavaScript - DOM Document
  • JavaScript - DOM Elements
  • JavaScript - DOM Forms
  • JavaScript - Changing HTML
  • JavaScript - Changing CSS
  • JavaScript - DOM Animation
  • JavaScript - DOM Navigation
  • JavaScript - DOM Collections
  • JavaScript - DOM Node Lists
  • JavaScript Miscellaneous
  • JavaScript - Ajax
  • JavaScript - Generators
  • JavaScript - Async Iteration
  • JavaScript - Atomics Objects
  • JavaScript - Rest Parameter
  • JavaScript - Page Redirect
  • JavaScript - Dialog Boxes
  • JavaScript - Page Printing
  • JavaScript - Validations
  • JavaScript - Animation
  • JavaScript - Multimedia
  • JavaScript - Image Map
  • JavaScript - Browsers
  • JavaScript - JSON
  • JavaScript - Multiline Strings
  • JavaScript - Date Formats
  • JavaScript - Get Date Methods
  • JavaScript - Set Date Methods
  • JavaScript - Random Number
  • JavaScript - Modules
  • JavaScript - Dynamic Imports
  • JavaScript - Export and Import
  • JavaScript - BigInt
  • JavaScript - Blob
  • JavaScript - Unicode
  • JavaScript - Execution Context
  • JavaScript - Shallow Copy
  • JavaScript - Call Stack
  • JavaScript - Design Patterns
  • JavaScript - Reference Type
  • JavaScript - LocalStorage
  • JavaScript - SessionStorage
  • JavaScript - IndexedDB
  • JavaScript - Clickjacking Attack
  • JavaScript - Currying
  • JavaScript - Graphics
  • JavaScript - Canvas
  • JavaScript - Debouncing
  • JavaScript - Common Mistakes
  • JavaScript - Performance
  • JavaScript - Best Practices
  • JavaScript - Style Guide
  • JavaScript - Ninja Code
  • JavaScript Useful Resources
  • JavaScript - Questions And Answers
  • JavaScript - Quick Guide
  • JavaScript - Resources
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

JavaScript Assignment Operators

The assignment operators in JavaScript are used to assign values to the variables. These are binary operators. An assignment operator takes two operands , assigns a value to the left operand based on the value of right operand. The left operand is always a variable and the right operand may be literal, variable or expression.

An assignment operator first evaluates the expression and then assign the value to the variable (left operand).

A simple assignment operator is equal (=) operator. In the JavaScript statement "let x = 10;", the = operator assigns 10 to the variable x.

We can combine a simple assignment operator with other type of operators such as arithmetic, logical, etc. to get compound assignment operators. Some arithmetic assignment operators are +=, -=, *=, /=, etc. The += operator performs addition operation on the operands and assign the result to the left hand operand.

Arithmetic Assignment Operators

In this section, we will cover simple assignment and arithmetic assignment operators. An arithmetic assignment operator performs arithmetic operation and assign the result to a variable. Following is the list of operators with example −

Assignment Operator Example Equivalent To
= (Assignment) a = b a = b
+= (Addition Assignment) a += b a = a + b
-= (Subtraction Assignment) a -= b a = a – b
*= (Multiplication Assignment) a *= b a = a * b
/= (Division Assignment) a /= b a = a / b
%= (Remainder Assignment) a %= b a = a % b
**= (Exponentiation Assignment) a **= b a = a ** b

Simple Assignment (=) Operator

Below is an example of assignment chaining −

Addition Assignment (+=) Operator

The JavaScript addition assignment operator performs addition on the two operands and assigns the result to the left operand. Here addition may be numeric addition or string concatenation.

In the above statement, it adds values of b and x and assigns the result to x.

Example: Numeric Addition Assignment

Example: string concatenation assignment, subtraction assignment (-=) operator.

The subtraction assignment operator in JavaScript subtracts the value of right operand from the left operand and assigns the result to left operand (variable).

In the above statement, it subtracts b from x and assigns the result to x.

Multiplication Assignment (*=) Operator

The multiplication assignment operator in JavaScript multiplies the both operands and assign the result to the left operand.

In the above statement, it multiplies x and b and assigns the result to x.

Division Assignment (/=) Operator

This operator divides left operand by the right operand and assigns the result to left operand.

In the above statement, it divides x by b and assigns the result (quotient) to x.

Remainder Assignment (%=) Operator

The JavaScript remainder assignment operator performs the remainder operation on the operands and assigns the result to left operand.

In the above statement, it divides x by b and assigns the result (remainder) to x.

Exponentiation Assignment (**=) Operator

This operator performs exponentiation operation on the operands and assigns the result to left operand.

In the above statement, it computes x**b and assigns the result to x.

JavaScript Bitwise Assignment operators

A bitwise assignment operator performs bitwise operation on the operands and assign the result to a variable. These operations perform two operations, first a bitwise operation and second the simple assignment operation. Bitwise operation is done on bit-level. A bitwise operator treats both operands as 32-bit signed integers and perform the operation on corresponding bits of the operands. The simple assignment operator assigns result is to the variable (left operand).

Following is the list of operators with example −

Assignment Operator Example Equivalent To
&= (Bitwise AND Assignment) a &= b a = a & b
|= (Bitwise OR Assignment) a |= b a = a | b
^= (Bitwise XOR Assignment) a ^= b a = a ^ b

Bitwise AND Assignment Operator

The JavaScript bitwise AND assignment (&=) operator performs bitwise AND operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs bitwise AND on x and b and assigns the result to the variable x.

Bitwise OR Assignment Operator

The JavaScript bitwise OR assignment (|=) operator performs bitwise OR operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs bitwise OR on x and b and assigns the result to the variable x.

Bitwise XOR Assignment Operator

The JavaScript bitwise XOR assignment (^=) operator performs bitwise XOR operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs bitwise XOR on x and b and assigns the result to the variable x.

JavaScript Shift Assignment Operators

A shift assignment operator performs bitwise shift operation on the operands and assign the result to a variable (left operand). These are a combinations two operators, the first bitwise shift operator and second the simple assignment operator.

Following is the list of the shift assignment operators with example −

Assignment Operator Example Equivalent To
<<= (Left Shift Assignment) a <<= b a = a << b
>>= (Right Shift Assignment) a >>= b a = a >> b
>>>= (Unsigned Right Shift Assignment) a >>>= b a = a >>> b

Left Shift Assignment Operator

The JavaScript left shift assignment (<<=) operator performs left shift operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs left shift on x and b and assigns the result to the variable x.

Right Shift Assignment Operator

The JavaScript right shift assignment (>>=) operator performs right shift operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs right shift on x and b and assigns the result to the variable x.

Unsigned Right Shift Assignment Operator

The JavaScript unsigned right shift assignment (>>>=) operator performs unsigned right shift operation on the operands and assigns the result to the left operand (variable).

In the above statement, it performs unsigned right shift on x and b and assigns the result to the variable x.

JavaScript Logical Assignment operators

In JavaScript, a logical assignment operator performs a logical operation on the operands and assign the result to a variable (left operand). Each logical assignment operator is a combinations two operators, the first logical operator and second the simple assignment operator.

Following is the list of the logical assignment operators with example −

Assignment Operator Example Equivalent To
&&= (Logical AND Assignment) a &&= b a = a && b
||= (Logical OR Assignment) a ||= b a = a || b
??= (Nullish Coalescing Assignment) a ??= b a = a ?? b

To Continue Learning Please Login

Home » JavaScript Tutorial » JavaScript Logical Assignment Operators

JavaScript Logical Assignment Operators

Summary : in this tutorial, you’ll learn about JavaScript logical assignment operators, including the logical OR assignment operator ( ||= ), the logical AND assignment operator ( &&= ), and the nullish assignment operator ( ??= ).

ES2021 introduces three logical assignment operators including:

  • Logical OR assignment operator ( ||= )
  • Logical AND assignment operator ( &&= )
  • Nullish coalescing assignment operator ( ??= )

The following table shows the equivalent of the logical assignments operator:

Logical Assignment OperatorsLogical Operators
x ||= yx || (x = y)
x &&= yx && (x = y)
x ??= yx ?? (x = y);

The Logical OR assignment operator

The logical OR assignment operator ( ||= ) accepts two operands and assigns the right operand to the left operand if the left operand is falsy:

In this syntax, the ||= operator only assigns y to x if x is falsy. For example:

In this example, the title variable is undefined , therefore, it’s falsy. Since the title is falsy, the operator ||= assigns the 'untitled' to the title . The output shows the untitled as expected.

See another example:

In this example, the title is 'JavaScript Awesome' so it is truthy. Therefore, the logical OR assignment operator ( ||= ) doesn’t assign the string 'untitled' to the title variable.

The logical OR assignment operator:

is equivalent to the following statement that uses the logical OR operator :

Like the logical OR operator, the logical OR assignment also short-circuits. It means that the logical OR assignment operator only performs an assignment when the x is falsy.

The following example uses the logical assignment operator to display a default message if the search result element is empty:

The Logical AND assignment operator

The logical AND assignment operator only assigns y to x if x is truthy:

The logical AND assignment operator also short-circuits. It means that

is equivalent to:

The following example uses the logical AND assignment operator to change the last name of a person object if the last name is truthy:

The nullish coalescing assignment operator

The nullish coalescing assignment operator only assigns y to x if x is null or undefined :

It’s equivalent to the following statement that uses the nullish coalescing operator :

The following example uses the nullish coalescing assignment operator to add a missing property to an object:

In this example, the user.nickname is undefined , therefore, it’s nullish. The nullish coalescing assignment operator assigns the string 'anonymous' to the user.nickname property.

The following table illustrates how the logical assignment operators work:

  • The logical OR assignment ( x ||= y ) operator only assigns y to x if x is falsy.
  • The logical AND assignment ( x &&= y ) operator only assigns y to x if x is truthy.
  • The nullish coalescing assignment ( x ??= y ) operator only assigns y to x if x is nullish.

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 Comparison and Logical Operators

JavaScript Ternary Operator

JavaScript Booleans

JavaScript Bitwise Operators

  • JavaScript Object.is()
  • JavaScript typeof Operator

JavaScript operators are special symbols that perform operations on one or more operands (values). For example,

Here, we used the + operator to add the operands 2 and 3 .

JavaScript Operator Types

Here is a list of different JavaScript operators you will learn in this tutorial:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • String Operators
  • Miscellaneous Operators

1. JavaScript Arithmetic Operators

We use arithmetic operators to perform arithmetic calculations like addition, subtraction, etc. For example,

Here, we used the - operator to subtract 3 from 5 .

Commonly Used Arithmetic Operators

Operator Name Example
Addition
Subtraction
Multiplication
Division
Remainder
Increment (increments by ) or
Decrement (decrements by ) or
Exponentiation (Power)

Example 1: Arithmetic Operators in JavaScript

Note: The increment operator ++ adds 1 to the operand. And, the decrement operator -- decreases the value of the operand by 1 .

To learn more, visit Increment ++ and Decrement -- Operators .

2. JavaScript Assignment Operators

We use assignment operators to assign values to variables. For example,

Here, we used the = operator to assign the value 5 to the variable x .

Commonly Used Assignment Operators

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponentiation Assignment

Example 2: Assignment Operators in JavaScript

3. javascript comparison operators.

We use comparison operators to 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 gives us
Not equal to gives us
Greater than gives us
Less than gives us
Greater than or equal to gives us
Less than or equal to gives us
Strictly equal to gives us
Strictly not equal to gives us

Example 3: Comparison Operators in JavaScript

The equality operators ( == and != ) convert both operands to the same type before comparing their values. For example,

Here, we used the == operator to compare the number 3 and the string 3 .

By default, JavaScript converts string 3 to number 3 and compares the values.

However, the strict equality operators ( === and !== ) do not convert operand types before comparing their values. For example,

Here, JavaScript didn't convert string 4 to number 4 before comparing their values.

Thus, the result is false , as number 4 isn't equal to string 4 .

4. JavaScript Logical Operators

We use logical operators to perform logical operations on boolean expressions. For example,

Here, && is the logical operator AND . Since both x < 6 and y < 5 are true , the combined result is 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

Example 4: Logical Operators in JavaScript

Note: We use comparison and logical operators in decision-making and loops. You will learn about them in detail in later tutorials.

More on JavaScript Operators

We use bitwise operators to perform binary operations on integers.

Operator Description Example
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Sign-propagating right shift
>>> Zero-fill right shift

Note: We rarely use bitwise operators in everyday programming. If you are interested, visit JavaScript Bitwise Operators to learn more.

In JavaScript, you can also use the + operator to concatenate (join) two strings. For example,

Here, we used the + operator to concatenate str1 and str2 .

JavaScript has many more operators besides the ones we listed above. You will learn about them in detail in later tutorials.

Operator Description Example
: Evaluates multiple operands and returns the value of the last operand.
: Returns value based on the condition.
Returns the data type of the variable.
Returns t if the specified object is a valid object of the specified class.
Discards any expression's return value.

Table of Contents

  • Introduction
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators

Video: JavaScript Operators

Sorry about that.

Related Tutorials

JavaScript Tutorial

  • Skip to main content
  • Select language
  • Skip to search
  • বাংলা (বাংলাদেশ)
  • Português (do Brasil)
  • Add a translation
  • Print this page
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

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

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

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

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

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

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

For example, 3+4 or x*y .

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

For example, x++ or ++x .

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

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

Compound assignment operators
Name Shorthand operator Meaning

Destructuring

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

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

Comparison operators
Operator Description Examples returning true
( ) Returns true if the operands are equal.

( ) Returns true if the operands are not equal.
( ) Returns true if the operands are equal and of the same type. See also and .
( ) Returns true if the operands are not equal and/or not of the same type.
( ) Returns true if the left operand is greater than the right operand.
( ) Returns true if the left operand is greater than or equal to the right operand.
( ) Returns true if the left operand is less than the right operand.
( ) Returns true if the left operand is less than or equal to the right operand.

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

In addition, JavaScript provides the arithmetic operators listed in the following table.

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to convert the operand to a number, if it is not already. returns .
returns

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

The following table summarizes JavaScript's bitwise operators.

Bitwise operators
Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same.
[Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

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

Bitwise operator examples
Expression Result Binary Description

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

Bitwise shift operators

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

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

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example
Left shift
( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
Sign-propagating right shift ( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
Zero-fill right shift ( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

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

Logical operators
Operator Usage Description
( ) (Logical AND) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) (Logical OR) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) (Logical NOT) Returns if its single operand can be converted to ; otherwise, returns .

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

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

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

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

Short-circuit evaluation

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

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

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

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

For example,

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

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

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

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

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

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

A unary operation is operation with only one operand.

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

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

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

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

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

Deleting array elements

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

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

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

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

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

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

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

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

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

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

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

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

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

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

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

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

Relational operators

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

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

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

The following examples show some uses of the in operator.

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

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

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

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

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

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

Operator precedence
Operator type Individual operators
member
call / create instance
negation/increment
multiply/divide
addition/subtraction
bitwise shift
relational
equality
bitwise-and
bitwise-xor
bitwise-or
logical-and
logical-or
conditional
assignment
comma

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

  • Expressions

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

Conceptually, there are two types of expressions: those that assign a value to a variable and those that simply have a value.

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

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

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

Primary expressions

Basic keywords and general expressions in JavaScript.

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

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

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

  • Grouping operator

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

Comprehensions

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

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

Left values are the destination of an assignment.

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

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

  • Spread operator

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

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

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • Standard built-in objects
  • ArrayBuffer
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.float32x4
  • SIMD.float64x2
  • SIMD.int16x8
  • SIMD.int32x4
  • SIMD.int8x16
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Property accessors
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Statements and declarations
  • Legacy generator function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template strings
  • Deprecated features
  • New in JavaScript
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript 7 support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Javatpoint Logo

JavaScript Tutorial

Javascript basics, javascript objects, javascript bom, javascript dom, javascript validation, javascript oops, javascript cookies, javascript events, exception handling, javascript misc, javascript advance, differences.

Interview Questions

JavaTpoint

JavaScript operators are symbols that are used to perform operations on operands. For example:

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as JavaScript arithmetic operators.

OperatorDescriptionExample
+Addition10+20 = 30
-Subtraction20-10 = 10
*Multiplication10*20 = 200
/Division 20/10 = 2
%Modulus (Remainder)20%10 = 0
++Incrementvar a=10; a++; Now a = 11
--Decrementvar a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators are as follows:

OperatorDescriptionExample
==Is equal to10==20 = false
===Identical (equal and of same type)10==20 = false
!=Not equal to10!=20 = true
!==Not Identical 20!==20 = false
>Greater than20>10 = true
>=Greater than or equal to20>=10 = true
20
20

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:

OperatorDescriptionExample
&Bitwise AND(10==20 & 20==33) = false
|Bitwise OR(10==20 | 20==33) = false
^Bitwise XOR(10==20 ^ 20==33) = false
~Bitwise NOT (~10) = -10
(10
>>Bitwise Right Shift(10>>2) = 2
>>>Bitwise Right Shift with Zero(10>>>2) = 2

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

OperatorDescriptionExample
&&Logical AND(10==20 && 20==33) = false
||Logical OR(10==20 || 20==33) = false
!Logical Not!(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

OperatorDescriptionExample
=Assign10+10 = 20
+=Add and assignvar a=10; a+=20; Now a = 30
-=Subtract and assignvar a=20; a-=10; Now a = 10
*=Multiply and assignvar a=10; a*=20; Now a = 200
/=Divide and assignvar a=10; a/=2; Now a = 5
%=Modulus and assignvar a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

OperatorDescription
(?:)Conditional Operator returns value based on the condition. It is like if-else.
,Comma Operator allows multiple expressions to be evaluated as single statement.
deleteDelete Operator deletes a property from the object.
inIn Operator checks if object has the given property
instanceofchecks if the object is an instance of given type
newcreates an instance (object)
typeofchecks the type of object.
voidit discards the expression's return value.
yieldchecks what is returned in a generator by the generator's iterator.

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

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.

JavaScript OR (||) variable assignment explanation

Given this snippet of JavaScript...

Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?

My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.

Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.

  • variable-assignment
  • or-operator

Bergi's user avatar

  • 4 Old question, but regarding PHP, there is a construct you can use: $f=$a or $f=$b or $f=$c; // etc . PHP has both the || operator and the or operator, which do the same job; however or is evaluated after assignment while || is evaluated before. This also give you the perlish style of $a=getSomething() or die('oops'); –  Manngo Oct 14, 2016 at 7:30
  • 1 In PHP 5.3 you can leave out the middle part of the ternary operator so basing from that... You can also cut that a bit shorter into something like this: $f = $a ?: $b ?: $c; –  Rei Nov 30, 2017 at 10:31
  • 1 As of PHP 7 you can use ?? for this. $a = $b ?? 'default' –  Spencer Ruskin Mar 19, 2018 at 23:09
  • @SpencerRuskin so $a will be assigned the value of $b if $b is true, other 'default' ? –  oldboy Mar 22, 2019 at 18:31
  • That's right. Look at the null coalescing operator section on this page: php.net/manual/en/migration70.new-features.php –  Spencer Ruskin Mar 29, 2019 at 14:54

12 Answers 12

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

Lightness Races in Orbit's user avatar

  • 62 Just mind the 'gotcha' which is that the last one will always get assigned even if they're all undefined, null or false. Setting something you know isn't false, null, or undefined at the end of the chain is a good way to signal nothing was found. –  Erik Reppen Aug 29, 2011 at 16:51
  • 1 I've seen this technique for years, but what striked me just then when I wanted to use it is that the result of the expression is not cast to boolean. You cannot later do if( true == f ) . If an integer was stored in f, then this test will always return false. –  user1115652 Aug 1, 2013 at 2:11
  • 10 Actually, you can do if(true == f) , which is the same as if(f) : the test will pass. If you want to also test the type of f , use strict comparison: if(true === f) , which will fail indeed. –  Alsciende Jun 6, 2016 at 9:44
  • 5 Yes, short-circuit evaluation is common. But the distinction here lies in the way JavaScript returns the last value that halted the execution. @Anurag's answer does a much better job of explaining this. –  Ben.12 Dec 1, 2017 at 21:58
  • not sure if that is the best explanation for beginners. I would recommend: javascript.info/logical-operators –  csguy Jun 7, 2020 at 20:43

This is made to assign a default value , in this case the value of y , if the x variable is falsy .

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator ( || ) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

Falsy values are those who coerce to false when used in boolean context, and they are 0 , null , undefined , an empty string, NaN and of course false .

Christian C. Salvadó's user avatar

  • 3 +1 Is there another operator like that? Or is || exclusive. –  OscarRyz Jun 21, 2010 at 21:13
  • 11 @Support (@Oscar): The Logical && operator has a similar behavior, it returns the value of the first operand if it's by itself falsy and returns the value of the second operand, only if the first one is truthy , e.g. ("foo" && "bar") == "bar" and (0 && "bar") == 0 –  Christian C. Salvadó Jun 21, 2010 at 21:18
  • 14 Falsy is in fact the technical term. –  ChaosPandion Jun 22, 2010 at 2:36
  • 10 So we learned about ||, &&, "Falsy" and "Truly" in this post. Best answer with "hidden" gifts. –  Alex Aug 20, 2015 at 12:36
  • 6 @Alex NB: "Truthy" (!"Truly") –  Bumpy Dec 3, 2016 at 6:20

Javacript uses short-circuit evaluation for logical operators || and && . However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true , or false value.

The following values are considered falsy in JavaScript.

  • "" (empty string)

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

The first 5 values are all truthy and get evaluated until it meets the first falsy value ( null ) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText , otherwise evaluate and return newMessagesText . Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages." .

Marjan Venema's user avatar

  • 48 This is the best answer in my opinion because of the following explanation: However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value. –  mastazi Dec 28, 2015 at 3:48
  • 1 @mastazi Yep, it should go in bold font IMHO. –  noober Jan 24, 2016 at 23:51
  • 6 Should be the answer, it shows the values being chosen over test cases. –  Aesthetic Sep 14, 2016 at 10:15
  • Agreed, this is my favorite answer as it specifically addresses JavaScript variable assignment concerns. Additionally, if you choose to use a ternary as one of the subsequent variables to test for assignment (after the operator) you must wrap the ternary in parentheses for assignment evaluation to work properly. –  Joey T Jan 29, 2019 at 21:19

Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

f is assigned the nearest value that is not equivalent to false . So 0, false, null, undefined, are all passed over:

Alsciende's user avatar

  • 13 Don't forget '' also equal false in this case. –  Brigand Apr 4, 2013 at 17:07
  • Upvote for pointing out that f is assigned the NEAREST value which is a pretty important point here. –  steviesh Jun 6, 2016 at 3:45
  • 3 "Nearest" isn't quite true, though it does have that appearance. The boolean || operator, being a boolean operator has two operands: a left side and a right side. If the left side of the || is truthy , the operation resolves to the left side and the right side is ignored. If the left side is falsy , it resolves to the right side. So null || undefined || 4 || 0 actually resolves to undefined || 4 || 0 which resolves to 4 || 0 which resolves to 4 . –  devios1 Oct 16, 2017 at 16:26
  • @devios1 but 4 is nearest –  milos Oct 19, 2021 at 9:13

There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a , it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

Marcin's user avatar

  • 6 In the pretty static language C# one can use the ?? operator á la: object f = a ?? b ?? c ?? d ?? e; –  herzmeister Jan 20, 2010 at 11:14
  • 2 herzmeister - thanks! I didn't know that ?? operator can be chained in C# and used in lazy evaluation techniques –  Marek Mar 8, 2012 at 8:49
  • 3 As mentioned elsewhere, that last d will be assigned whether or not it was null/undefined or not. –  BlackVegetable Jul 2, 2013 at 17:17
  • One slight correction: the || operator always resolves to the whole right side operand when the left side is falsy. Being a boolean operator it only sees two inputs: the left side and the right side. The parser doesn't see them as a series of terms, so it doesn't actually stop when it finds the first truthy value unless that value is also the left hand operand of another || . –  devios1 Oct 16, 2017 at 16:38

This question has already received several good answers.

In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.

Using this technique is not good practice for several reasons; however.

Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.

Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.

Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:

() ? value 1: Value 2.

Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.

Community's user avatar

  • potentially be targeted for change in the future. yes, but I don't that applies for javascript. –  Aesthetic Sep 14, 2016 at 10:17
  • Came here and saw all the above answers and was thinking to myself that something just looked off about the assignment. I've just been reading Clean Code by Robert C Martin and this type of assignment definitely violates the "Have no Side Effects" rule...while the author himself states that his book is only one of many techniques for generating good code, I was still surprised that no one else objected to this kind of assignment. +1 –  Albert Rothman Sep 20, 2016 at 23:50
  • Thank you for the response. I think more people need to consider side effects when writing code, but until someone has spent a lot of time maintaining other people's code. They often don't consider it. –  WSimpson Sep 27, 2016 at 13:53
  • 2 You really think that monstrosity is clearer than a || b || c || d || e ? –  devios1 Oct 16, 2017 at 16:41
  • 1 @AlbertRothman I don't see any side effects. Nothing is being mutated. It's simply a shorthand for null coalescing, which is a quite common feature in many languages. –  devios1 Oct 16, 2017 at 16:43

Return output first true value .

If all are false return last false value.

Arshid KV's user avatar

Its called Short circuit operator.

Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

It could also be used to set a default value for function argument.`

Vijay's user avatar

It's setting the new variable ( z ) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

Matthew Crumley's user avatar

It means that if x is set, the value for z will be x , otherwise if y is set then its value will be set as the z 's value.

it's the same as

It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

Andris's user avatar

  • 5 this is wrong! if (x) { z = x; } else {z = y;} if the first value is false, the second value is always assigned not depending what the value actually is. –  evilpie Jun 21, 2010 at 20:13
  • Except that I think it just assigns y to z if x is false . That's the way it works for me in FF, of course, that might be implementation dependent, too. –  tvanfosson Jun 21, 2010 at 20:15
  • 7 The last part about returning false isn't true (no pun intended). If the first value is falsey, the || operator just returns the second value, regardless of whether it's truthy or not. –  Matthew Crumley Jun 21, 2010 at 20:15
  • -1. Your equivalent code snippet is accurate, but the important point is that z gets set to the value of x if that value is truthy . Otherwise it gets set to the value of y . This means that if x is set to, for example, 0 , or the empty string "" , this doesn’t do what you say, since those values are falsy . –  Daniel Cassidy Sep 27, 2010 at 16:56

It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

Will output 'bob';

tvanfosson's user avatar

  • 1 You should clarify what you mean by ‘empty’. Empty strings coerce to false , but empty arrays or objects coerce to true . –  Daniel Cassidy Sep 27, 2010 at 16:58
  • @Daniel "null, empty, or 0" -- null would apply with respect to arrays and objects. Point taken, though. –  tvanfosson Sep 27, 2010 at 17:01

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): " lightweight normalization of cross-browser differences "

Alon Brontman'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 variables variable-assignment or-operator or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Best way to halve 12V battery voltage for 6V device, while still being able to measure the battery level?
  • Do we know how the SpaceX Starship stack handles engine shutdowns?
  • A phrase that means you are indifferent towards the things you are familiar with?
  • Is the barrier to entry for mathematics research increasing, and is it at risk of becoming less accessible in the future?
  • Why does the proposed Lunar Crater Radio Telescope suggest an optimal latitude of 20 degrees North?
  • Why "Power & battery" stuck at spinning circle for 4 hours?
  • How often does systemd journal collect/read logs from sources
  • Could a 200m diameter asteroid be put into a graveyard orbit and not be noticed by people on the ground?
  • Where do UBUNTU_CODENAME and / or VERSION_CODENAME come from?
  • How do I snap the edges of hex tiles together?
  • Dispute cancellation fees by 3rd-party airline booking
  • Regarding upper numbering of ramification groups
  • How to make Bash remove quotes after parameter expansion?
  • Why don't professors seem to use learning strategies like spaced repetition and note-taking?
  • Why is killing even evil brahmins categorized as 'brahma hatya'?
  • Who are the mathematicians interested in the history of mathematics?
  • I'm looking for a series where there was a civilization in the Mediterranean basin, which got destroyed by the Atlantic breaking in
  • A Fantasy story where a man appears to have been crushed on his wedding night by a statue on the finger of which he has put a wedding ring
  • What scientific evidence there is that keeping cooked meat at room temperature is unsafe past two hours?
  • Unicode character └ (U+2514) not set up with LaTeX (when using) pandoc with markdown text file
  • What is the frequentist's Bayesian prior for a coin with unknown bias
  • Times New Roman Ligatures are not working in Overleaf
  • A question about syntactic function of the clause
  • Advice on DIY Adjusting Rheem Water Heater Thermostat

which operator following type of assignment operator in javascript

  • Programming

Rahul Awati

  • Rahul Awati

What is an operator in mathematics and programming?

In mathematics and computer programming , an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.

Depending on its type, an operator manipulates an arithmetic or logical value, or operand, in a specific way to generate a specific result. From handling simple arithmetic functions to facilitating the execution of complex algorithms, like security encryption , operators play an important role in the programming world.

Mathematical and logical operators should not be confused with a system operator , or sysop, which refers to a person operating a server or the hardware and software in a computing system or network.

Operators and logic gates

In computer programs, Boolean operators are among the most familiar and commonly used sets of operators. These operators work only with true or false values and include the following:

These operators and variations, such as XOR, are used in logic gates .

Boolean operators can also be used in online search engines , like Google. For example, a user can enter a phrase like "Galileo AND satellite" -- some search engines require the operator be capitalized in order to generate results that provide combined information about both Galileo and satellite.

Types of operators

There are many types of operators used in computing systems and in different programming languages. Based on their function, they can be categorized in six primary ways.

1. Arithmetic operators

Arithmetic operators are used for mathematical calculations. These operators take numerical values as operands and return a single unique numerical value, meaning there can only be one correct answer.

The standard arithmetic operators and their symbols are given below.

+

Addition (a+b)

This operation adds both the operands on either side of the + operator.

-

Subtraction (a-b)

This operation subtracts the right-hand operand from the left.

*

Multiplication (a*b)

This operation multiplies both the operands.

/

Division (a/b)

This operation divides the left-hand operand by the operand on the right.

%

Modulus (a%b)

This operation returns the remainder after dividing the left-hand operand by the right operand.

2. Relational operators

Relational operators are widely used for comparison operators. They enter the picture when certain conditions must be satisfied to return either a true or false value based on the comparison. That's why these operators are also known as conditional operators.

The standard relational operators and their symbols are given below.

==

Equal (a==b)

This operator checks if the values of both operands are equal. If yes, the condition becomes TRUE.

!=

Not equal (a!=b)

This operator checks if the values of both operands are equal. If not, the condition becomes TRUE.

>

Greater than (a>b)

This operator checks if the left operand value is greater than the right. If yes, the condition becomes TRUE.

<

Less than (a<b)

This operator checks if the left operand is less than the value of right. If yes, the condition becomes TRUE.

>=

Greater than or equal (a>=b)

This operator checks if the left operand value is greater than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

<=

Less than or equal (a<=b)

This operator checks if the left operand value is less than or equal to the value of the right. If either condition is satisfied, the operator returns a TRUE value.

3. Bitwise operators

Bitwise operators are used to manipulate bits and perform bit-level operations . These operators convert integers into binary before performing the required operation and then showing the decimal result.

The standard bitwise operators and their symbols are given below.

&

Bitwise AND (a&b)

This operator copies a bit to the result if it exists in both operands. So, the result is 1 only if both bits are 1.

|

Bitwise OR (a|b)

This operator copies a bit to the result if it exists in either operand. So, the result is 1 if either bit is 1.

^

Bitwise XOR (a^b)

This operator copies a bit to the result if it exists in either operand. So, even if one of the operands is TRUE, the result is TRUE. However, if neither operand is TRUE, the result is FALSE.

~

Bitwise NOT (~a)

This unary operator flips the bits (1 to 0 and 0 to 1).

4. Logical operators

Logical operators play a key role in programming because they enable a system or program to take specific decisions depending on the specific underlying conditions. These operators take Boolean values as input and return the same as output.

The standard logical operators and their symbols are given below.

&&

Logical AND (a&&b)

This operator returns TRUE only if both the operands are TRUE or if both the conditions are satisfied. It not, it returns FALSE.

||

(a||b)

This operator returns TRUE if either operand is TRUE. It also returns TRUE if both the operands are TRUE. If neither operand is true, it returns FALSE.

!

Logical NOT (!a)

This unary operator returns TRUE if the operand is FALSE and vice versa. It is used to reverse the logical state of its (single) operand.

5. Assignment operators

Assignment operators are used to assign values to variables. The left operand is a variable, and the right is a value -- for example, x=3.

The data types of the variable and the value must match; otherwise, the program compiler raises an error, and the operation fails.

The standard assignment operators and their symbols are given below.

=

Assignment (a=b)

This operator assigns the value of the right operand to the left operand (variable).

+=

Add and assign (a+=b)

This operator adds the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a+b.

-=

Subtract and assign (a-=b)

This operator subtracts the right operand from the left operand and assigns the result to the left operand.

Logically, the operator means a=a-b.

*=

Multiply and assign (a*=b)

This operator multiplies the right operand and the left operand and assigns the result to the left operand.

Logically, the operator means a=a*b.

/=

Divide and assign (a/=b)

This operator divides the left operand and the right operand and assigns the result to the left operand.

Logically, the operator means a=a/b.

%=

Modulus and assign (a%=b)

This operator performs the modulus operation on the two operands and assigns the result to the left operand.

Logically, the operator means a=a%b.

6. Increment/decrement operators

The increment/decrement operators are unary operators, meaning they require only one operand and perform an operation on that operand. They sometimes are called monadic operators .

The standard increment/decrement operators and their symbols are given below.

++

Post-increment (a++)

This operator increments the value of the operand by 1 after using its value.

--

Post-decrement (a--)

This operator decrements the value of the operand by 1 after using its value.

++

Pre-increment (++a)

This operator increments the value of the operand by 1 before using its value.

--

Pre-decrement (--a)

This operator decrements the value of the operand by 1 before using its value.

See also: proximity operator , search string , logical negation symbol , character and mathematical symbols .

Continue Reading About operator

  • How to become a good Java programmer without a degree
  • How improving your math skills can help in programming
  • 10 best IT certs for beginners
  • Top 22 cloud computing skills to boost your career in 2022
  • Binary and hexadecimal numbers explained for developers

Related Terms

NBASE-T Ethernet is an IEEE standard and Ethernet-signaling technology that enables existing twisted-pair copper cabling to ...

SD-WAN security refers to the practices, protocols and technologies protecting data and resources transmitted across ...

Net neutrality is the concept of an open, equal internet for everyone, regardless of content consumed or the device, application ...

A proof of concept (PoC) exploit is a nonharmful attack against a computer or network. PoC exploits are not meant to cause harm, ...

A virtual firewall is a firewall device or service that provides network traffic filtering and monitoring for virtual machines (...

Cloud penetration testing is a tactic an organization uses to assess its cloud security effectiveness by attempting to evade its ...

Regulation SCI (Regulation Systems Compliance and Integrity) is a set of rules adopted by the U.S. Securities and Exchange ...

Strategic management is the ongoing planning, monitoring, analysis and assessment of all necessities an organization needs to ...

IT budget is the amount of money spent on an organization's information technology systems and services. It includes compensation...

ADP Mobile Solutions is a self-service mobile app that enables employees to access work records such as pay, schedules, timecards...

Director of employee engagement is one of the job titles for a human resources (HR) manager who is responsible for an ...

Digital HR is the digital transformation of HR services and processes through the use of social, mobile, analytics and cloud (...

A virtual agent -- sometimes called an intelligent virtual agent (IVA) -- is a software program or cloud service that uses ...

A chatbot is a software or computer program that simulates human conversation or "chatter" through text or voice interactions.

Martech (marketing technology) refers to the integration of software tools, platforms, and applications designed to streamline ...

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

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

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

OperatorDescriptionSyntax
+Addition: adds two operandsx + y
Subtraction: subtracts two operandsx – y
*Multiplication: multiplies two operandsx * y
/Division (float): divides the first operand by the secondx / y
//Division (floor): divides the first operand by the secondx // y
%Modulus: returns the remainder when the first operand is divided by the secondx % y
**Power: Returns first raised to power secondx ** y

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

OperatorDescriptionSyntax
>Greater than: True if the left operand is greater than the rightx > y
<Less than: True if the left operand is less than the rightx < y
==Equal to: True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to True if the left operand is greater than or equal to the rightx >= y
<=Less than or equal to True if the left operand is less than or equal to the rightx <= y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

OperatorDescriptionSyntax
andLogical AND: True if both the operands are truex and y
orLogical OR: True if either of the operands is true x or y
notLogical NOT: True if the operand is false not x

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

OperatorDescriptionSyntax
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

OperatorDescriptionSyntax
=Assign the value of the right side of the expression to the left side operand x = y + z
+=Add AND: Add right-side operand with left-side operand and then assign to left operanda+=b     a=a+b
-=Subtract AND: Subtract right operand from left operand and then assign to left operanda-=b     a=a-b
*=Multiply AND: Multiply right operand with left operand and then assign to left operanda*=b     a=a*b
/=Divide AND: Divide left operand with right operand and then assign to left operanda/=b     a=a/b
%=Modulus AND: Takes modulus using left and right operands and assign the result to left operanda%=b     a=a%b
//=Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operanda//=b     a=a//b
**=Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operanda**=b     a=a**b
&=Performs Bitwise AND on operands and assign value to left operanda&=b     a=a&b
|=Performs Bitwise OR on operands and assign value to left operanda|=b     a=a|b
^=Performs Bitwise xOR on operands and assign value to left operanda^=b     a=a^b
>>=Performs Bitwise right shift on operands and assign value to left operanda>>=b     a=a>>b
<<=Performs Bitwise left shift on operands and assign value to left operanda <<= b     a= a << b

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

which operator following type of assignment operator in javascript

Announcing UNISTR and || operator in Azure SQL Database – preview

which operator following type of assignment operator in javascript

Abhiman Tiwari

June 4th, 2024 0 0

We are excited to announce that the UNISTR intrinsic function and ANSI SQL concatenation ope ra tor ( || ) are now available in public preview in Azure SQL Database. The UNISTR function allows you to escape Unicode characters, making it easier to work with international text. The ANSI SQL concatenation ope ra tor ( || ) provides a simple and intuitive way to combine characters or binary strings. These new features will enhance your ability to manipulate and work with text data.  

What is UNISTR function?

The UNISTR function takes a text literal or an expression of characters and Unicode values, that resolves to character data and returns it as a UTF-8 or UTF-16 encoded string . This function allows you to use Unicode codepoint escape sequences with other characters in the string. The escape sequence for a Unicode character can be specified in the form of \ xxxx or \+ xxxxxx , where xxxx is a valid UTF-16 codepoint value, and xxxxxx is a valid Unicode codepoint value. This is especially useful for inserting data into NCHAR columns.  

The syntax of the UNISTR function is as follows:

  • The data type of character_expression could be char ,  nchar ,  varchar , or  nvarchar . For  char and  varchar  data types, the collation should be a valid UTF-8 collation only.
  • A single character representing a user-defined Unicode escape sequence. If not supplied, the default value is \.

Example #1:

For example, the following query returns the Unicode character for the specified value:

——————————-

Example #2:  

In this example, the UNISTR function is used with a user-defined escape character ( $ ) and a VARCHAR data type with UTF-8 collation.

I ♥ Azure SQL.

The legacy collations with code page can be identified using the query below:

What is ANSI SQL concatenation operator (||)?

The ANSI SQL concatenation ope ra tor ( || ) concatenates two or more characters or binary strings, columns, or a combination of strings and column names into one expression . The || ope ra tor does not honor the SET CONCAT_NULL_YIELDS_NULL option and always behaves as if the ANSI SQL behavior is enabled . This ope ra tor will work with character strings or binary data of any supported SQL Server collation . The || ope ra tor supports compound assignment || = similar to += . If the ope ra nds are of incompatible collation, then an error will be thrown. The collation behavior is identical to the CONCAT function  of character string data.

The syntax of the string concatenation operator is as follows:

  • The expression is a character or binary expression. Both expressions must be of the same data type, or one expression must be able to be implicitly converted to the data type of the other expression. If one ope ra nd is of binary type, then an unsupported ope ra nd type error will be thrown.

Example #1:  

For example, the following query concatenates two strings and returns the result:

Hello World!

Example #2:

In this example, multiple character strings are concatenated. If at least one input is a character string, non-character strings will be implicitly converted to character strings.

full_name order_details                                                                                                         item_desc

Josè Doe Order-1001~TS~Jun 1 2024 6:25AM~442A4706-0002-48EC-84FC-8AF27XXXX NULL

Example #3:  

In the example below, concatenating two or more binary strings and also compounding with T-SQL assignment operator.

V1          B1    B2

0x1A2B       0x4E  0xAE8C602E951AC245ADE767A23C834704A5

Example #4:  

As shown in the example below, using the || operator with only non-character types or combining binary data with other types is not supported.

Above queries will fail with error messages as below –  

In this blog post, we have introduced the UNISTR function and ANSI SQL concatenation operator (||) in Azure SQL Database.  The UNISTR function allows you to escape Unicode characters, making it easier to work with international text. ANSI SQL concatenation operator (||) provides a simple and intuitive way to combine characters or binary data. These new features will enhance your ability to manipulate and work with text data efficiently.  

We hope you will explore these enhancements, apply them in your projects, and share your feedback with us to help us continue improving.   Thank you!

which operator following type of assignment operator in javascript

Abhiman Tiwari Senior Product Manager, Azure SQL

authors

Leave a comment Cancel reply

Log in to start the discussion.

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

COMMENTS

  1. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  2. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  3. JavaScript Assignment Operators

    JavaScript remainder assignment operator (%=) assigns the remainder to the variable after dividing a variable by the value of the right operand. Syntax: Operator: x %= y Meaning: x = x % y Below example illustrate the Remainder assignment(%=) Operator in JavaScript: Example 1: The following example demonstrates if the given number is divisible by 4

  4. JavaScript Operators

    JavaScript Assignment Operators. Assignment operators assign values to JavaScript variables. The Addition Assignment Operator (+=) adds a value to a variable. ... JavaScript Type Operators. Operator Description; typeof: Returns the type of a variable: instanceof: Returns true if an object is an instance of an object type:

  5. JavaScript Assignment Operators

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

  6. Assignment operators

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

  7. Expressions and operators

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

  8. Assignment Operators in JavaScript

    An assignment operator requires two operands. The value of the right operand is assigned to the left operand. The sign = denotes the simple assignment operator.

  9. JavaScript Assignment Operators

    The JavaScript Assignment operators are used to assign values to the declared variables. Equals (=) operator is the most commonly used assignment operator. For example: var i = 10; The below table displays all the JavaScript assignment operators. JavaScript Assignment Operators. Example. Explanation. =.

  10. Operator precedence

    This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5, a.k.a. right operand of the assignment. As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

  11. JavaScript

    A simple assignment operator is equal (=) operator. In the JavaScript statement "let x = 10;", the = operator assigns 10 to the variable x. We can combine a simple assignment operator with other type of operators such as arithmetic, logical, etc. to get compound assignment operators. Some arithmetic assignment operators are +=, -=, *=, /=, etc.

  12. JavaScript Logical Assignment Operators

    The logical OR assignment operator ( ||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy: In this syntax, the ||= operator only assigns y to x if x is falsy. For example: console .log(title); Code language: JavaScript (javascript) Output: In this example, the title variable is undefined ...

  13. JavaScript Operators (with Examples)

    JavaScript operators are special symbols that perform operations on one or more operands (values). In this tutorial, you will learn about JavaScript operators with the help of examples. ... JavaScript Operator Types. ... JavaScript Assignment Operators. We use assignment operators to assign values to variables. For example, let x = 5;

  14. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. A complete and detailed list of operators and expressions is also available in the reference. Operators. JavaScript has the following types of operators.

  15. Which equals operator (== vs ===) should be used in JavaScript

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

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

  17. JavaScript operators

    JavaScript operators are symbols that are used to perform operations on operands. For example: var sum=10+20; var sum=10+20; Here, + is the arithmetic operator and = is the assignment operator. There are following types of operators in JavaScript. Arithmetic Operators.

  18. Assignment operators

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

  19. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

  20. Expressions and operators

    void. The void operator evaluates an expression and discards its return value. typeof. The typeof operator determines the type of a given object. +. The unary plus operator converts its operand to Number type. -. The unary negation operator converts its operand to Number type and then negates it. ~.

  21. What is an operator in programming?

    In mathematics and computer programming, an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming. Depending on its type, an operator manipulates ...

  22. Python Operators

    In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /, etc.

  23. Announcing UNISTR and || operator in Azure SQL Database

    The data type of character_expression could be char, nchar, varchar, or nvarchar. For char and varchar data types, the collation should be a valid UTF-8 collation only. A single character representing a user-defined Unicode escape sequence. If not supplied, the default value is \. Examples Example #1:

  24. Grammar and types

    You can declare a variable in two ways: With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables, depending on the execution context. With the keyword const or let. For example, let y = 13. This syntax can be used to declare a block-scope local variable.

  25. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if ...

  26. JavaScript reference

    The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals ...