• Skip to main content

UDN Web Docs: MDN Backup

  • Left shift assignment (<<=)

The left shift assignment operator ( <<= ) moves the specified amount of bits to the left and assigns the result to the variable.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Using left shift assignment

Specifications.

Specification

Browser compatibility

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
Left shift assignment ( )Chrome 1Edge 12Firefox 1IE 3Opera 3Safari 1WebView Android 1Chrome Android 18Firefox Android 4Opera Android 10.1Safari iOS 1Samsung Internet Android 1.0nodejs 0.1.100
  • Assignment operators in the JS guide
  • Left shift operator
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side JavaScript frameworks
  • Client-side web APIs
  • 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:
  • AggregateError
  • ArrayBuffer
  • AsyncFunction
  • BigInt64Array
  • BigUint64Array
  • FinalizationRegistry
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • ReferenceError
  • SharedArrayBuffer
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Addition (+)
  • Addition assignment (+=)
  • Assignment (=)
  • Bitwise AND (&)
  • Bitwise AND assignment (&=)
  • Bitwise NOT (~)
  • Bitwise OR (|)
  • Bitwise OR assignment (|=)
  • Bitwise XOR (^)
  • Bitwise XOR assignment (^=)
  • Comma operator (,)
  • Conditional (ternary) operator
  • Decrement (--)
  • Destructuring assignment
  • Division (/)
  • Division assignment (/=)
  • Equality (==)
  • Exponentiation (**)
  • Exponentiation assignment (**=)
  • Function expression
  • Greater than (>)
  • Greater than or equal (>=)
  • Grouping operator ( )
  • Increment (++)
  • Inequality (!=)
  • Left shift (<<)
  • Less than (<)
  • Less than or equal (<=)
  • Logical AND (&&)
  • Logical AND assignment (&&=)
  • Logical NOT (!)
  • Logical OR (||)
  • Logical OR assignment (||=)
  • Logical nullish assignment (??=)
  • Multiplication (*)
  • Multiplication assignment (*=)
  • Nullish coalescing operator (??)
  • Object initializer
  • Operator precedence
  • Optional chaining (?.)
  • Pipeline operator (|>)
  • Property accessors
  • Remainder (%)
  • Remainder assignment (%=)
  • Right shift (>>)
  • Right shift assignment (>>=)
  • Spread syntax (...)
  • Strict equality (===)
  • Strict inequality (!==)
  • Subtraction (-)
  • Subtraction assignment (-=)
  • Unary negation (-)
  • Unary plus (+)
  • Unsigned right shift (>>>)
  • Unsigned right shift assignment (>>>=)
  • async function expression
  • class expression
  • delete operator
  • function* expression
  • in operator
  • new operator
  • void operator
  • async function
  • for await...of
  • function declaration
  • import.meta
  • try...catch
  • Arrow function expressions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • Private class fields
  • Public class fields
  • constructor
  • 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: "x" is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: X.prototype.y called on incompatible type
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an 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: cannot use "in" operator to search for "x" in "y"
  • TypeError: cyclic object value
  • TypeError: invalid "instanceof" 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

JS Tutorial

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

Assignment operators assign values to JavaScript variables.

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

Shift Assignment Operators

Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

The = Operator

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

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

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

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

Right Shift Assignment Example

The >>>= operator.

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

Unsigned Right Shift Assignment Example

The &= operator.

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

Bitwise AND Assignment Example

The |= operator.

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

Bitwise OR Assignment Example

The ^= operator.

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

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

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

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

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

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

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

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

This page is Ready to Use

left shift assignment

Moves the specified number of bits to the left and assigns the result to result. The bits vacated by the operation are filled with 0.

Using the <<= operator is the same as specifying result = result << expression

Other articles

  • Bitwise Left Shift Operator (<<)
  • Bitwise Right Shift Operator (>>)
  • Unsigned Right Shift Operator (>>>)

Attributions

Microsoft Developer Network: Article

  • Accessibility

Left shift (<<)

The << operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.

Description

The << operator is overloaded for two types of operands: number and BigInt . For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt left shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number left shift. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

The operator operates on the left operand's bit representation in two's complement . For example, 9 << 2 yields 36:

Bitwise a 32-bit integer x to the left by y bits yields x * 2 ** y . So for example, 9 << 3 is equivalent to 9 * (2 ** 3) = 9 * (8) = 72 .

If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 << 32 is the same as 100 << 0 (and produces 100 ) because 32 modulo 32 is 0.

For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading 0 bits, and negative BigInts having an infinite number of leading 1 bits.

Left shifting any number x by 0 returns x converted to a 32-bit integer. Do not use << 0 to truncate numbers to integers; use Math.trunc() instead.

Using left shift

Specifications.

Specification

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Opera Safari Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet WebView Android Deno Node.js
1 12 1 3 1 18 4 10.1 1 1.0 4.4 1.0 0.10.0
  • Bitwise operators in the JS guide
  • Left shift assignment ( <<= )

© 2005–2023 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift

  • JavaScript - Home
  • JavaScript - Introduction
  • JavaScript - Comments
  • JavaScript - Operators
  • JavaScript - If Else
  • JavaScript - Switch
  • JavaScript - While Loop
  • JavaScript - For Loop
  • JavaScript - For In Loop
  • JavaScript - For Of Loop
  • JavaScript - Continue Statement
  • JavaScript - Break Statement
  • JavaScript - Label Statement
  • JavaScript - Functions
  • JavaScript - Math
  • JavaScript - Array
  • JavaScript - Q&A

AlphaCodingSkills

Facebook Page

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

JavaScript - left shift operator assignment

The Bitwise left shift assignment operator (<<=) assigns the first operand a value equal to the result of Bitwise left shift operation of two operands.

(x <<= y) is equivalent to (x = x << y)

The Bitwise left shift operator (<<) takes the two numbers and left shift the bits of first operand by number of place specified by second operand. For example: for left shifting the bits of x by y places, the expression ( x<<y ) can be used. It is equivalent to multiplying x by 2 y .

The example below describes how left shift operator works:

The code of using left shift operator (<<) is given below:

The output (value of txt ) after running above script will be:

Example: Count number of 1 Bits in a positive integer

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

Bitwise AND operation with 1 at any bit results into 1 if the bit is 1 or 0 if the bit is 0. Performing such operation at every bit, and counting the number of 1 gives the count of 1 bits in the given positive integer. To achieve this bitwise left shift assignment operator can be used as shown in the example below:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

James Hibbard

Demystifying JavaScript Operators: What Does That Symbol Mean?

Share this article

Demystifying JavaScript Operators: What Does That Symbol Mean?

What are JavaScript Operators?

A quick word on terminology, arithmetic operators, assignment operators, comparison operators, logical operators, bitwise operators, other operators, frequently asked questions (faqs) about javascript operators.

In this article, we’re going to examine the operators in JavaScript one by one. We’ll explain their function and demonstrate their usage, helping you to grasp their role in building more complex expressions.

JavaScript, a cornerstone of modern web development, is a robust language full of numerous features and constructs. Among these, operators (special symbols such as + , += , && , or ... ) play an essential role, enabling us to perform different types of calculations and manipulations on variables and values.

Despite their importance, operators can sometimes be a source of confusion for new programmers and seasoned coders alike.

Take a moment to examine this code snippet:

Don’t be alarmed if it seems a bit cryptic. By the time we’re finished, you’ll be able to understand exactly what it does.

Before we dive in, let’s clarify a couple of terms that we’ll be using quite a bit:

An operand is the item that operators work on. If we think of an operator as a kind of action, the operand is what the action is applied to. For example, in the expression 5 + 3, + is the operator (the action of addition), and 5 and 3 are the operands — the numbers being added together. In JavaScript, operands can be of various types, such as numbers, strings, variables, or even more complex expressions.

Coercion is the process of converting a value from one primitive type to another. For example, JavaScript might change a number into a string, or a non-Boolean value into a Boolean. The primitive types in JavaScript are String , Number , BigInt , Boolean , undefined , Symbol or null .

NaN stands for Not a Number . It’s a special value of the Number type that represents an invalid or unrepresentable numeric value.

Truthy values are those that evaluate to true in a Boolean context, while falsy values evaluate to false — with falsy values being false , 0 , -0 , '' , null , undefined , NaN and BigInt(0) . You can read more about truthy and falsy values in Truthy and Falsy Values: When All is Not Equal in JavaScript .

As we explore JavaScript operators, we’ll see these concepts in action and get a better understanding of how they influence the results of our operations.

Arithmetic operators allow us to perform arithmetic operations on values and to transform data. The commonly used arithmetic operators in JavaScript include addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Beyond these, we also have the modulus operator ( % ), which returns the remainder of a division operation, and the increment ( ++ ) and decrement ( -- ) operators that modify a value by one.

Addition: +

The addition operator performs two distinct operations: numeric addition and string concatenation. When evaluating expressions using the + operator, JavaScript first coerces both operands to primitive values. Once this is done, it examines the types of both operands.

If one operand is a string, the other operand is also converted to a string, and then the two strings are concatenated. For example:

If both operands are BigInts , BigInt addition is performed. A BigInt is a special numeric type that can deal with numbers larger than the standard Number type can handle.

But if one operand is a BigInt and the other isn’t, JavaScript throws a TypeError :

For all other cases, both operands are converted to numbers, and numeric addition is performed. For example:

Be aware that JavaScript sometimes has a strange idea of what this looks like:

In this case, JavaScript tried to convert the object { a: 1 } to a primitive value, but the best it could do was to convert it to the string [object Object] , which then got concatenated with the number 1.

Subtraction: -

The subtraction operator in JavaScript is straightforward in its usage: it’s used to subtract one number from another. Like the addition operator, it also works with the BigInt type.

If both operands are numbers or can be converted to numbers, JavaScript performs numeric subtraction:

If both operands are BigInts , JavaScript performs BigInt subtraction:

Like the addition operator, subtraction can also produce unexpected results when used with non-numbers. For example, if we try to subtract a something that can’t be converted to a number, JavaScript will return NaN , which stands for “Not a Number”:

Multiplication: *

The multiplication operator works with numbers and BigInts.

Normally, we’ll be multiplying numbers:

If both operands are BigInts , then it performs BigInt multiplication:

As with other operators, JavaScript attempts to convert non-numeric values into numbers. If it can’t do this, it returns NaN :

Division: /

The division operator ( / ) functions with numbers and BigInts , much the same way as + , - and * . It first converts both operands into numbers.

Standard number division:

When dealing with BigInts , the division operator behaves slightly differently. It performs the division and discards any remainder, effectively truncating the result towards zero:

Dividing a number by zero will produce Infinity , unless it’s a BigInt , in which case it throws a RangeError .

If we attempt to divide a number by a value that can’t be converted into a number, JavaScript will usually return NaN .

Modulus (remainder): %

The modulus operator is used to find the remainder after division of one number by another (known as the dividend and the divisor ). This arithmetic operator works with numbers and BigInts .

When we use the % operator, JavaScript first converts the operands to numbers:

This is because three goes into ten three times (making nine), and what’s left over (the remainder) is one.

A common use case for this operator is to check if a number is odd or even:

This uses an arrow function and the triple equals operator that we’ll meet later on.

The modulus operator has some special cases. For example, if one of the operands is NaN , if the dividend is Infinity , or if the divisor is 0 , the operation returns NaN .

On the other hand, if the divisor is Infinity or if the dividend is 0 , the operation returns the dividend.

Increment: ++

The increment operator is used to increase the value of a variable by 1. It can be applied to operands of type Number or BigInt , and its behavior can differ based on whether it’s used in postfix or prefix form.

Postfix increment

If the operator is placed after the operand ( num++ ), the increment operation is performed after the value is returned. In this case, the original value of the variable is used in the current expression, and the variable’s value is incremented afterward:

Prefix increment

If the operator is placed before the operand ( ++num ), the increment operation is performed before the value is returned. In this case, the variable’s value is incremented first, and then the updated value is used in the current expression:

Decrement: --

The decrement operator is used to decrease the value of a variable by 1. Similar to the increment operator, it can be applied to operands of type Number or BigInt . The behavior of the decrement operator can vary based on whether it’s used in postfix or prefix form.

Postfix decrement

When the operator is placed after the operand ( num-- ), the decrement operation is performed after the value is returned. In this case, the original value of the variable is used in the current expression, and the variable’s value is decremented afterward:

Prefix decrement

When the operator is placed before the operand ( --num ), the decrement operation is performed before the value is returned. In this case, the variable’s value is decremented first, and then the updated value is used in the current expression:

The decrement operator, just like the increment operator, can only be used with variables that can be changed:

Miscellaneous arithmetic operators

In addition to the increment and decrement operators, there are other arithmetic operators in JavaScript that we should be aware of.

The unary negation operator ( - ) is used to negate a numeric value, changing its sign to the opposite. For example, -5 would be the negation of the number 5 .

The unary plus operator ( + ) can be used to explicitly convert a value to a number, which can be useful when dealing with string representations of numbers. For example, +'10' converts the string '10' to the number 10 :

The exponentiation operator ( ** ) is used to raise a number to a power. For example, 2 ** 3 represents 2 raised to the power of 3, which results in 8.

It’s also important to note that JavaScript follows operator precedence rules, which determine the order in which operators are evaluated in an expression. For example, multiplication and division have a higher precedence than addition and subtraction, so they are evaluated first:

We can alter the order of evaluation by using the grouping operator () , which is covered in the “ Grouping operator ” section below.

Assignment operators are used to assign values to variables. They also offer a concise and effective way to update the value of a variable based on an expression or other value. In addition to the basic assignment operator ( = ), JavaScript provides compound assignment operators that combine arithmetic or logical operations with assignment.

Assignment: =

This operator is used to assign a value to a variable. It allows us to store a value in a variable so that we can use and reference it later in our code:

The assignment operator assigns the value on the right-hand side of the operator to the variable on the left-hand side.

Additionally, the = operator can be chained to assign the same value to multiple variables in a single line:

Addition assignment: +=

The addition assignment operator is a compound operator that performs an operation and assignment in one step. Specifically, it adds the right operand to the left operand and then assigns the result to the left operand:

This operator isn’t limited to numbers. It can also be used for string concatenation:

When the operands aren’t of the same type, JavaScript applies the same rules of type coercion that we saw previously:

Subtraction assignment: -=

The subtraction assignment operator is another compound operator that performs an operation and assignment in one step. It subtracts the right operand from the left operand and then assigns the result to the left operand:

Like other JavaScript operators, -= performs type coercion when the operands aren’t of the same type. If an operand can be converted to a number, JavaScript will do so:

Otherwise, the result is NaN :

Multiplication assignment: *=

The multiplication assignment operator multiplies the left operand by the right operand and then assigns the result back to the left operand:

When we use operands of different types, JavaScript will try to convert non-numeric string operands to numbers:

If the string operand can’t be converted to a number, the result is NaN .

Division assignment: /=

Like its siblings, the division assignment operator performs an operation on the two operands and then assigns the result back to the left operand:

Otherwise, the rules we discussed for the division operator above apply:

Modulus assignment: %=

The modulus assignment operator performs a modulus operation on the two operands and assigns the result to the left operand:

Otherwise, the rules we discussed for the modulus operator apply:

Exponentiation assignment: **=

The exponentiation assignment operator performs exponentiation, where the left operand is the base and the right operand is the exponent, and assigns the result to the left operand:

Here, num is raised to the power of 3, and the result (8) is assigned back to num .

As before, when the second operand is not a number, JavaScript will attempt to convert it with varying degrees of success:

Bitwise assignment operators

While we’ve been focusing on arithmetic operators so far, JavaScript also supports a set of assignment operators that work at the bit level. These are the bitwise assignment operators . If you’re familiar with binary numbers and bit manipulation, these operators will be right up your alley.

These operators include:

  • Bitwise AND assignment ( &= )
  • Bitwise OR assignment ( |= )
  • Bitwise XOR assignment ( ^= )
  • Left shift assignment ( <<= )
  • Right shift assignment ( >>= )
  • Unsigned right shift assignment ( >>>= )

Each of these JavaScript assignment operators performs a specific bitwise operation on the binary representations of the numbers involved and assigns the result back to the left operand.

We’ll explore bitwise operators in more detail in the “ Bitwise Operators ” section below.

Leaving the realm of arithmetic, let’s dive into another significant group of JavaScript operators — the comparison operators. As the name implies, comparison operators are used to compare values and return a Boolean result. Comparison operators are the underpinning of many programming decisions and control structures — from simple condition checks to complex logical operations.

Equality: ==

The equality operator is used to check whether two values are equal to each other. It returns a Boolean result. However, it’s important to note that this comparison operator performs a loose equality check, meaning that if the operands are of different types, JavaScript will try to convert them to a common type before making the comparison:

Things get slightly more complicated dealing with objects and arrays. The == operator checks whether they refer to the same location in memory, not whether their contents are identical:

In this case, JavaScript doesn’t attempt to convert and compare the values within the objects or arrays. Instead, it checks whether they’re the same object (that is, whether they occupy the same memory space).

You can read more about loose equality comparisons here .

Inequality: !=

The inequality operator is used to check whether two values are not equal to each other. Like the == operator, it performs a loose inequality check. This means that, if they’re of different types, it will try to convert the operands to a common type before making the comparison:

Similar to the == operator, when comparing objects and arrays, the != operator checks whether they refer to the same memory location, not whether their content is identical.

Strict equality ( === ) and strict inequality ( !== )

The strict equality and strict inequality comparison operators are similar to their non-strict counterparts ( == and != ), but they don’t perform type coercion. If the operands are of different types, they’re considered different, no matter their values.

Here’s how they work:

For objects and arrays, the strict equality operator behaves the same way as the loose equality operator: it checks whether they refer to the same object, not whether their contents are identical.

NaN is a special case. It’s the only value in JavaScript that isn’t strictly equal to itself:

You can read more about strict equality comparisons here .

Greater than: >

The greater than operator checks if the left operand is greater than the right operand, returning a Boolean result. This comparison is straightforward with numeric values:

When comparing non-numeric values, JavaScript applies a process of conversion to make them comparable. If both values are strings, they’re compared based on their corresponding positions in the Unicode character set:

If one or both of the operands aren’t strings, JavaScript tries to convert them to numeric values for the comparison:

Certain special rules apply for specific values during this conversion. For instance, null is converted to 0 , undefined is converted to NaN , and Boolean values true and false are converted to 1 and 0 respectively. However, if either value is NaN after conversion, the operator will always return false :

Less than: <

The less than operator returns true if the left operand is less than the right operand, and false otherwise. The same rules apply as for the greater than operator; only the order of operands is reversed:

Like the > operator, the < operator uses coercion to convert operands to a common type before making the comparison.

Greater than or equal to ( >= ) and less than or equal to ( <= )

The greater than or equal to ( >= ) and less than or equal to ( <= ) operators function similarly to their < and > counterparts, with the added condition of equality.

For the >= operator, it returns true if the left operand is greater than or equal to the right operand, and false otherwise. Conversely, the <= operator returns true if the left operand is less than or equal to the right operand, and false otherwise. Coercion rules and type conversion, as explained in the sections on < and > directly above, apply here as well:

Logical operators in JavaScript offer a way to work with multiple conditions simultaneously. They’re an integral part of decision-making constructs in programming, such as if statements, and for loops.

Mastering logical operators is key for controlling the flow of our code.

Logical AND: &&

When used with Boolean values, the logical AND operator returns true if all conditions are true and false otherwise.

However, with non-Boolean values, it gets more interesting:

  • The operator evaluates conditions from left to right.
  • If it encounters a value that can be converted to false (known as a falsy value), it stops and returns that value.
  • If all values are truthy, it returns the last truthy value.

For example:

The && operator’s ability to return the value of the operands makes it a versatile tool for conditional execution and setting default values. For example, we can use the && operator to execute a function or a block of code only if a certain condition is met:

In this case, renderWelcomeMessage will only be executed if userIsLoggedIn is true . If userIsLoggedIn is false , the operation will stop at userIsLoggedIn and renderWelcomeMessage won’t be called. This pattern is often used with React to conditionally render components.

Logical OR: ||

When used with Boolean values, the logical OR operator returns true if at least one condition is true and false otherwise.

It can also return non-Boolean values, performing what’s known as short-circuit evaluation . It evaluates conditions from left to right, stopping and returning the value of the first truthy condition encountered. If all conditions are falsy, it returns the last falsy value:

Logical NOT: !

The logical NOT operator is used to reverse the Boolean value of a condition or expression. Unlike the && and || operators, the ! operator always returns a Boolean value.

If the condition is truthy (that is, it can be converted to true ), the operator returns false . If the condition is falsy (that is, it can be converted to false ), the operator returns true :

We can use the ! operator twice to convert a value to its Boolean equivalent:

Nullish coalescing operator: ??

The nullish coalescing operator checks whether the value on its left is null or undefined , and if so, it returns the value on the right. Otherwise, it returns the value on the left.

Though similar to the || operator in some respects, the ?? operator differs in its handling of falsy values.

Whereas the || operator returns the right-hand operand if the left-hand operand is any falsy value (such as null , undefined , false , 0 , NaN , '' ), the ?? operator only does so when the left-hand operand is null or undefined :

Setting default values with logical operators

The || and ?? logical operators are useful for setting default values in programs. Here’s an example of doing this with the || operator:

Here’s an example with the ?? operator:

The main difference between these logical operators (as highlighted above) is how they treat falsy values:

Bitwise operators in JavaScript offer a way to perform operations at the binary level, directly manipulating bits in a number’s binary representation. While these operators can be instrumental in specific tasks like data encoding, decoding, and processing, they’re not frequently used in day-to-day JavaScript programming.

In this article, we’ll provide an overview of these operators so you can recognize and understand them, but we won’t delve deeply into their usage given their relatively niche application.

Bitwise AND: &

The bitwise AND operator performs a bitwise AND operation on the binary representations of integers. It returns a new number whose bits are set to 1 if the bits in the same position in both operands are 1. Otherwise, it sets them to 0:

Bitwise OR: |

The bitwise OR operator works similarly to the & operator, but it sets a bit to 1 if at least one of the bits in the same position in the operands is 1:

Bitwise XOR: ^

The bitwise XOR operator is a little different. It sets a bit to 1 only if the bits in the same position in the operands are different (one is 1 and the other is 0):

Bitwise NOT: ~

The bitwise NOT operator ( ~ ) inverts the bits of its operand. It switches 1s to 0s and 0s to 1s in the binary representation of a number:

Note: two’s complement is a method for representing negative integers in binary notation.

Bitwise shift operators: <<, >>, >>>

Bitwise shift operators are used to shift the bits of a binary number to the left or right. In JavaScript, there are three types: left shift ( << ), right shift ( >> ), and zero-fill right shift ( >>> ).

The left shift bitwise operator ( << ) moves bits to the left and fills in with zeros on the right. The right shift operator ( >> ) shifts bits to the right, discarding bits shifted off. The zero-fill right shift operator ( >>> ) also shifts bits to the right but fills in zeros on the left.

These operators are less common in everyday JavaScript coding, but they have uses in more specialized areas like low-level programming, binary data manipulation, and some types of mathematical calculations.

Apart from the commonly used arithmetic, comparison, logical, and bitwise operators, JavaScript offers a variety of unique operators for specific purposes. These include operators for handling conditional logic, managing object properties, controlling the order of operations, and more.

Conditional (ternary) operator: ? :

The conditional ternary operator ( ? : ) is a concise way to make decisions in our JavaScript code. It gets its name from being the only operator that takes three operands. The syntax for this conditional operator is as follows:

The operator works by first evaluating the condition. If the condition is true , it executes the expressionIfTrue , and if it’s false , it executes the expressionIfFalse :

In the code above, the ternary operator checks if age is greater than or equal to 18. Since age is 15, the condition evaluates to false , and 'Minor' is assigned to the status variable.

This operator can be a handy way to write concise if–else statements, but it can also make code more difficult to read if overused or used in complex conditions.

Spread operator: ...

The spread operator ( ... ) allows elements of an iterable (such as an array or a string) to be expanded in places where zero or more arguments or elements are expected. It can be used in function calls, array literals, and object literals:

The spread operator can be a handy tool for creating copies of arrays or objects, concatenating arrays, or passing the elements of an array as arguments to a function.

You can read more about the spread operator in Quick Tip: How to Use the Spread Operator in JavaScript .

Comma operator: ,

The comma operator ( , ) allows multiple expressions to be evaluated in a sequence and returns the result of the last expression. The expressions are evaluated from left to right.

It’s particularly useful when we need to include multiple expressions in a location that only allows for one, such as in the initialization or update sections of a for loop:

In the code above, the comma operator is used to declare and update two variables ( i and j ) in the for loop.

Optional chaining operator: ?.

Optional chaining is a relatively recent addition to JavaScript (as of ES2020) that simplifies the process of accessing deeply nested properties of objects. It helps us to write cleaner and safer code by providing a way to attempt to retrieve a property value without having to explicitly check if each reference in its chain exists:

In the above example, user?.address?.city accesses the city property of user.address if user and user.address both exist. Otherwise, it returns undefined . This approach avoids a common pitfall in JavaScript, where trying to access a property of undefined or null leads to a TypeError :

Before optional chaining, JavaScript developers had to use lengthy conditional logic to avoid such errors:

Pipeline operator: |>

The pipeline operator ( |> ) is intended to improve the readability of code that would otherwise be written with nested function calls. Essentially, it allows us to take the result of one expression and feed it into the next. This is particularly useful when we’re applying a series of transformations to a value:

With the pipeline operator, we’re able rewrite this code like so:

Be aware that, at the time of writing, the pipeline operator is at stage 2 of the ECMAScript proposal process , meaning it’s a draft and is undergoing further iteration and refinement.

Grouping operator: ()

The grouping operator ( () ) in JavaScript is used to change the precedence of evaluation in expressions. This operator doesn’t perform any operations on its value, but it controls the order in which calculations are carried out within an expression.

For example, multiplication and division have higher precedence than addition and subtraction. This means that, in an expression such as 2 + 3 * 4 , the multiplication is done first, resulting in 2 + 12 , and then the addition is performed, giving a result of 14 .

If we want to change the order of operations, we can use the grouping operator. For example, if we want the addition to be done before the multiplication in the previous example, we could write (2 + 3) * 4 . In this case, the addition is performed first, resulting in 5 * 4 , and then the multiplication is performed, giving a result of 20.

The grouping operator allows us to ensure that operations are performed in the order we intend, which can be critical in more complex mathematical or logical expressions.

We’ve spent this article delving into the broad and sometimes complex world of JavaScript operators. These operators enable us to manipulate data, control program flow, and carry out complex computations.

Understanding these operators is not a mere academic exercise; it’s a practical skill that can enhance our ability to write and understand JavaScript.

Remember the confusing code snippet we started with? Let’s revisit that and see if it makes more sense now:

In plain English, this code is finding the maximum of three numbers, x , y , and z .

It does this by using a combination of JavaScript’s ternary operator ( ? : ) and comparison operators ( > ).

Here’s how it works:

  • The expression (x > y ? x : y) checks whether x is greater than y .
  • If x is greater than y , it returns x ; otherwise, it returns y . In other words, it’s getting the maximum of x and y .
  • This result (the maximum of x and y ) is then compared to z with the > operator.
  • If the maximum of x and y is greater than z , then second ternary (x > y ? x : y) is evaluated.
  • In this ternary, x and y are compared once again and the greater of the two is returned.
  • Otherwise, if z is greater than the maximum of x and y , then z is the maximum of the three numbers, and it’s returned.

If you found this explanation confusing, that’s because it is. Nesting ternary operators like this isn’t very readable and the calculation could be better expressed using Math.max :

Nonetheless, understanding how JavaScript operators work is like learning the grammar of a new language. It can be challenging at first, but once we’ve grasped the basics, we’ll be constructing complex sentences (or in our case, code) with ease.

Before I go, if you found this guide helpful and are looking to dive deeper into JavaScript, why not check out Learn to Code with JavaScript over on SitePoint Premium. This book is an ideal starting point for beginners, teaching not just JavaScript — the world’s most popular programming language — but also essential coding techniques that can be applied to other programming languages.

It’s a fun and easy-to-follow guide that will turn you from a novice to a confident coder in no time.

Happy coding!

What are the different types of JavaScript operators and how are they used?

JavaScript operators are symbols that are used to perform operations on operands (values or variables). There are several types of operators in JavaScript, including arithmetic, assignment, comparison, logical, bitwise, string, ternary, and special operators. Each type of operator has a specific function. For example, arithmetic operators are used to perform mathematical operations, while assignment operators are used to assign values to variables. Comparison operators are used to compare two values, and logical operators are used to determine the logic between variables or values.

How does the assignment operator work in JavaScript?

The assignment operator in JavaScript is used to assign values to variables. It is represented by the “=” symbol. For example, if you have a variable named “x” and you want to assign the value “10” to it, you would write “x = 10”. This means that “x” now holds the value “10”. There are also compound assignment operators that perform an operation and an assignment in one step. For example, “x += 5” is the same as “x = x + 5”.

What is the difference between “==” and “===” in JavaScript?

In JavaScript, “==” and “===” are comparison operators, but they work slightly differently. The “==” operator compares the values of two operands for equality, after converting both operands to a common type. On the other hand, the “===” operator, also known as the strict equality operator, compares both the value and the type of the operands. This means that “===” will return false if the operands are of different types, even if their values are the same.

How do logical operators work in JavaScript?

Logical operators in JavaScript are used to determine the logic between variables or values. There are three logical operators: AND (&&), OR (||), and NOT (!). The AND operator returns true if both operands are true, the OR operator returns true if at least one of the operands is true, and the NOT operator returns the opposite of the operand.

What is the purpose of the ternary operator in JavaScript?

The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false. The syntax is “condition ? value_if_true : value_if_false”. For example, “x = (y > 5) ? 10 : 20” means that if “y” is greater than 5, “x” will be assigned the value 10; otherwise, “x” will be assigned the value 20.

How are bitwise operators used in JavaScript?

Bitwise operators in JavaScript operate on 32-bit binary representations of the number values. They perform bit-by-bit operations on these binary representations. There are several bitwise operators, including AND (&), OR (|), XOR (^), NOT (~), left shift (<<), right shift (>>), and zero-fill right shift (>>>). These operators can be used for tasks such as manipulating individual bits in a number, which can be useful in certain types of programming, such as graphics or cryptography.

What are string operators in JavaScript?

In JavaScript, the plus (+) operator can be used as a string operator. When used with strings, the + operator concatenates (joins together) the strings. For example, “Hello” + ” World” would result in “Hello World”. There is also a compound assignment string operator (+=) that can be used to add a string to an existing string. For example, “text += ‘ World'” would add ” World” to the end of the existing string stored in the “text” variable.

What are special operators in JavaScript?

Special operators in JavaScript include the conditional (ternary) operator, the comma operator, the delete operator, the typeof operator, the void operator, and the in operator. These operators have specific uses. For example, the typeof operator returns a string indicating the type of a variable or value, and the delete operator deletes a property from an object.

How does operator precedence work in JavaScript?

Operator precedence in JavaScript determines the order in which operations are performed when an expression involves multiple operators. Operators with higher precedence are performed before those with lower precedence. For example, in the expression “2 + 3 * 4”, the multiplication is performed first because it has higher precedence than addition, so the result is 14, not 20.

Can you explain how increment and decrement operators work in JavaScript?

Increment (++) and decrement (–) operators in JavaScript are used to increase or decrease a variable’s value by one, respectively. They can be used in a prefix form (++x or –x) or a postfix form (x++ or x–). In the prefix form, the operation is performed before the value is returned, while in the postfix form, the operation is performed after the value is returned. For example, if x is 5, ++x will return 6, but x++ will return 5 (although x will be 6 the next time it is accessed).

Network admin, freelance web developer and editor at SitePoint .

SitePoint Premium

  |     |        
  

.

.

The (<<=) operator is used to shift the bits of an expression to the left.

The operator syntax has these parts:

operator is exactly the same as specifying:

The <<= operator shifts the bits of result left by the number of bits specified in expression . For example:

The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56 (00111000 in binary). Bits are filled in with zeroes when shifting.

For information on when a run-time error is generated by the <<= operator, see the Operator Behavior table.

See also: << Operator , >> Operator , >>> Operator , Operator Behavior , Operator Precedence , Operator Summary

C Point Pty Ltd. All Rights Reserved.

TutorialsTonight Logo

JAVASCRIPT ASSIGNMENT OPERATORS

In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.

Assignment Operators

In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

The assignment operators are used to assign value based on the right operand to its left operand.

The left operand must be a variable while the right operand may be a variable, number, boolean, string, expression, object, or combination of any other.

One of the most basic assignment operators is equal = , which is used to directly assign a value.

javascript assignment operator

Assignment Operators List

Here is the list of all assignment operators in JavaScript:

In the following table if variable a is not defined then assume it to be 10.

Operator Description Example Equivalent to
= a = 10 a = 10
+= a += 10 a = a + 10
-= a -= 10 a = a - 10
*= a *= 10 a = a * 10
/= a /= 10 a = a / 10
%= a %= 10 a = a % 10
**= a **= 2 a = a ** 2
<<= a <<= 1 a = a << 1
>>= a >>= 2 a = a >> 2
>>>= a >>>= 1 a = a >>> 1
&= a &= 4 a = a & 4
|= a |= 2 a = a | 2
^= a ^= 5 a = a ^ 5
&&= a &&= 3 a = a && 3
||= a ||= 4 a = a || 4
??= a ??= 2 a = a ?? 2

Assignment operator

The assignment operator = is the simplest value assigning operator which assigns a given value to a variable.

The assignment operators support chaining, which means you can assign a single value in multiple variables in a single line.

Addition assignment operator

The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand.

On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

Subtraction assignment operator

The subtraction assignment operator -= subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

If the value can not be subtracted then it results in a NaN .

Multiplication assignment operator

The multiplication assignment operator *= assigns the result to the left operand after multiplying values of the left and right operand.

Division assignment operator

The division assignment operator /= divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

Remainder assignment operator

The remainder assignment operator %= assigns the remainder to the left operand after dividing the value of the left operand by the value of the right operand.

Exponentiation assignment operator

The exponential assignment operator **= assigns the result of exponentiation to the left operand after exponentiating the value of the left operand by the value of the right operand.

Left shift assignment

The left shift assignment operator <<= assigns the result of the left shift to the left operand after shifting the value of the left operand by the value of the right operand.

Right shift assignment

The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Unsigned right shift assignment

The unsigned right shift assignment operator >>>= assigns the result of the unsigned right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Bitwise AND assignment

The bitwise AND assignment operator &= assigns the result of bitwise AND to the left operand after ANDing the value of the left operand by the value of the right operand.

Bitwise OR assignment

The bitwise OR assignment operator |= assigns the result of bitwise OR to the left operand after ORing the value of left operand by the value of the right operand.

Bitwise XOR assignment

The bitwise XOR assignment operator ^= assigns the result of bitwise XOR to the left operand after XORing the value of the left operand by the value of the right operand.

Logical AND assignment

The logical AND assignment operator &&= assigns value to left operand only when it is truthy .

Note : A truthy value is a value that is considered true when encountered in a boolean context.

Logical OR assignment

The logical OR assignment operator ||= assigns value to left operand only when it is falsy .

Note : A falsy value is a value that is considered false when encountered in a boolean context.

Logical nullish assignment

The logical nullish assignment operator ??= assigns value to left operand only when it is nullish ( null or undefined ).

how left shift assignment operator works in javascript

  • HTML Tutorial
  • HTML Exercises
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • DOM Audio/Video
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter

JavaScript Unsigned Right Shift Assignment Operator

In JavaScript “>>>=” is known as the unsigned right shift assignment bitwise operator . This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable.

Return value: It returns the number after shifting of bits.

Example 1: This example shows the basic use of the Javascript Unsigned Right Shift Assignment Operator.

Example 2: Using a variable to store the return value by >>> operator.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

What does a bitwise shift (left or right) do and what is it used for?

I've seen the operators >> and << in various code that I've looked at (none of which I actually understood), but I'm just wondering what they actually do and what some practical uses of them are.

If the shifts are like x * 2 and x / 2 , what is the real difference from actually using the * and / operators? Is there a performance difference?

  • bit-manipulation
  • bitwise-operators

Peter Mortensen's user avatar

  • 6 Googling for "bitwise shift" and looking at the first result (Wikipedia) probably isn't that hard. It also answers all of the above. –  Jon Commented Jun 17, 2011 at 12:38
  • 1 Yes, off-course there should be a performance difference. Please see this [link] ( dotnetperls.com/shift ) –  Waqas Shabbir Commented Jul 23, 2015 at 5:12
  • 9 Possible duplicate of What are bitwise shift (bit-shift) operators and how do they work? –  TylerH Commented Oct 19, 2015 at 20:06

9 Answers 9

Here is an applet where you can exercise some bit-operations, including shifting.

You have a collection of bits, and you move some of them beyond their bounds:

It is filled from the right with fresh zeros. :)

Filled from the left. A special case is the leading 1. It often indicates a negative value - depending on the language and datatype. So often it is wanted, that if you shift right, the first bit stays as it is.

And it is conserved over multiple shifts:

If you don't want the first bit to be preserved, you use (in Java, Scala, C++, C as far as I know, and maybe more) a triple-sign-operator:

There isn't any equivalent in the other direction, because it doesn't make any sense - maybe in your very special context, but not in general.

Mathematically, a left-shift is a *=2, 2 left-shifts is a *=4 and so on. A right-shift is a /= 2 and so on.

user unknown's user avatar

  • 7 ANSI C defines only the two bitwise shift operators >> and <<. –  TML Commented Jun 17, 2011 at 20:01
  • 1 @TML: ANSI C isn't the only language which uses bitwise shift operators. C++ uses them too and Java does, doesn't it? I guess there are even more languages. and I don't ses "C" in the headlinen, nor in the text or tags of the question. –  user unknown Commented Jan 20, 2015 at 20:16
  • 2 No, the question doesn't; which is why I still upvoted you. But at the time (admittedly, this was almost 4 years ago) I felt it was a valuable comment to add. :) –  TML Commented Jan 22, 2015 at 2:11
  • Does it go 2 4 6 8 or 2 4 8 16 ? –  S.S. Anne Commented Apr 29, 2019 at 23:13
  • @JL2210: Don't you have the possibility to try it out? Or to calculate it with pen and paper? Since I wrote *=2, and not +=2, it should be the latter, shouldn't it? –  user unknown Commented Apr 30, 2019 at 22:18

Left bit shifting to multiply by any power of two and right bit shifting to divide by any power of two.

For example, x = x * 2; can also be written as x<<1 or x = x*8 can be written as x<<3 (since 2 to the power of 3 is 8). Similarly x = x / 2; is x>>1 and so on.

Nitish's user avatar

x = x * 2^value (normal operation)

x << value (bit-wise operation)

x = x * 16 (which is the same as 2^4 )

The left shift equivalent would be x = x << 4

Right Shift

x = x / 2^value (normal arithmetic operation)

x >> value (bit-wise operation)

x = x / 8 (which is the same as 2^3 )

The right shift equivalent would be x = x >> 3

Till Helge's user avatar

Left shift : It is equal to the product of the value which has to be shifted and 2 raised to the power of number of bits to be shifted.

Right shift : It is equal to quotient of value which has to be shifted by 2 raised to the power of number of bits to be shifted.

Raghu's user avatar

Left bit shifting to multiply by any power of two. Right bit shifting to divide by any power of two.

In C/C++ it can be written as,

Pabitra Dash's user avatar

The bit shift operators are more efficient as compared to the / or * operators.

In computer architecture, divide(/) or multiply(*) take more than one time unit and register to compute result, while, bit shift operator, is just one one register and one time unit computation.

Shobhit Raj's user avatar

  • Isn't there one-cycle multiplication with modern CPUs? –  Peter Mortensen Commented Aug 14, 2020 at 16:15

Some examples:

  • Bit operations for example converting to and from Base64 (which is 6 bits instead of 8)
  • doing power of 2 operations ( 1 << 4 equal to 2^4 i.e. 16)
  • Writing more readable code when working with bits. For example, defining constants using 1 << 4 or 1 << 5 is more readable.

Aliostad's user avatar

Yes, I think performance-wise you might find a difference as bitwise left and right shift operations can be performed with a complexity of o(1) with a huge data set.

For example, calculating the power of 2 ^ n:

Similar code with a bitwise left shift operation would be like:

Moreover, performing a bit-wise operation is like exacting a replica of user level mathematical operations (which is the final machine level instructions processed by the microcontroller and processor).

Here is an example:

R.M.VIVEK Arni'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 bit-manipulation bitwise-operators bit-shift or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • We've made changes to our Terms of Service & Privacy Policy - July 2024

Hot Network Questions

  • Star Gold additional baggage allowance on connecting JetBlue flight from Air India
  • Is it safe to keep an expired credit card?
  • Can you be resurrected while your soul is under the effect of Magic Jar?
  • Compact rotatable connection that supports pull forces?
  • Is there any airplane that doesn't use a headset but speakers?
  • ORCA 6 slower than ORCA 5?
  • Are there any non-conjugation "extendible automorphisms" in the category of finite groups?
  • Singed Random Numbers
  • What techniques are there for preventing radio-signal replay attacks?
  • Merged columns not showing
  • Is excluding some parts of proposal in Phd. dissertation acceptable?
  • Can a possessive adjective (tuum) be used as a predicate accusative?
  • Can multi-threading improve performance of an IO-bound process?
  • Why are the Founders in Star Trek: Deep Space Nine considered so powerful?
  • Does spring stop applying force as soon as we cut it?
  • Asymptotics of sum involving square roots
  • How would tunneling mold tunnel?
  • How does lycanthropy interact with the clone spell?
  • Is there any family history for Klaus Stortebeker?
  • DC motor pump always transports in same direction, regardless of polarity
  • What might be causing ls to ignore LS_COLORS for setgid (sg, g+s) directories?
  • Efficient way to remove nailed-down plywood flooring in attic without damaging it?
  • Why doesn't Oppenheimer like the word "bomb" being used to describe the bomb?
  • Why have SIGPIPE when EPIPE exists?

how left shift assignment operator works in javascript

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Unsigned right shift (>>>)

The unsigned right shift ( >>> ) operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes 0 , so the resulting number is always positive. Unsigned right shift does not accept BigInt values.

Description

Unlike other arithmetic and bitwise operators, the unsigned right shift operator does not accept BigInt values. This is because it fills the leftmost bits with zeroes, but conceptually, BigInts have an infinite number of leading sign bits, so there's no "leftmost bit" to fill with zeroes.

The operator operates on the left operand's bit representation in two's complement . Consider the 32-bit binary representations of the decimal (base 10) numbers 9 and -9 :

The binary representation under two's complement of the negative decimal (base 10) number -9 is formed by inverting all the bits of its opposite number, which is 9 and 00000000000000000000000000001001 in binary, and adding 1 .

In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number 9 , the leftmost bit of the binary representation is 0 , and for the negative decimal number -9 , the leftmost bit of the binary representation is 1 .

Given those binary representations of the decimal (base 10) numbers 9 , and -9 :

For the positive number 9 , zero-fill right shift and sign-propagating right shift yield the same result: 9 >>> 2 yields 2 , the same as 9 >> 2 :

Notice how two rightmost bits, 01 , have been shifted off, and two zeroes have been shifted in from the left.

However, notice what happens for -9 : -9 >> 2 ( sign-propagating right shift ) yields -3 , but -9 >>> 2 (zero-fill right shift) yields 1073741821:

Notice how two rightmost bits, 11 , have been shifted off. For -9 >> 2 ( sign-propagating right shift ), two copies of the leftmost 1 bit have been shifted in from the left, which preserves the negative sign. On the other hand, for -9 >>> 2 (zero-fill right shift), zeroes have instead been shifted in from the left, so the negative sign of the number is not preserved, and the result is instead a (large) positive number.

If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, 100 >>> 32 is the same as 100 >>> 0 (and produces 100 ) because 32 modulo 32 is 0.

Using unsigned right shift

Unsigned right shift doesn't work with BigInts.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Bitwise operators in the JS guide
  • Unsigned right shift assignment ( >>>= )

IMAGES

  1. JavaScript Bitwise Operators (with Examples)

    how left shift assignment operator works in javascript

  2. Assignment Operator in JavaScript

    how left shift assignment operator works in javascript

  3. JavaScript Assignment Operators

    how left shift assignment operator works in javascript

  4. Assignment operators in Javascript

    how left shift assignment operator works in javascript

  5. Javascript Assignment Operators (with Examples)

    how left shift assignment operator works in javascript

  6. Javascript-assignment -operators

    how left shift assignment operator works in javascript

VIDEO

  1. Shift assessment video assignment

  2. .shift()

  3. Bitwise Left Shift Operator With negative Number In JAVA For Beginners

  4. Mastering Zero Fill Right Shift in JavaScript: A Key to Efficient Coding

  5. Javascript Masterclass #25 Ternary Operator

  6. Does ANYONE Understand How This Works in JavaScript?

COMMENTS

  1. Left Shift Assignment (<<=) Operator in JavaScript

    The Left Shift Assignment Operator is represented by "<<=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number.

  2. Left shift assignment (<<=)

    The left shift assignment (<<=) operator performs left shift on the two operands and assigns the result to the left operand. Skip to main content; Skip to search; Skip to select language ... JavaScript. Learn to run scripts in the browser. Accessibility. Learn to make the web accessible to all. Plus Plus. Overview. A customized MDN experience.

  3. Left Shift Assignment

    Assignment operators in the JS guide. Left shift ( <<) The <<= operator performs left shift on the two operands and assigns the result to the left operand.

  4. Left shift assignment (<<=)

    Left shift assignment (<<=) The left shift assignment operator ( <<=) moves the specified amount of bits to the left and assigns the result to the variable. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone.

  5. Left shift assignment (<<=)

    The left shift assignment operator ( <<=) moves the specified amount of bits to the left and assigns the result to the variable.

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

  7. left shift assignment · WebPlatform Docs

    left shift assignment Summary. Moves the specified number of bits to the left and assigns the result to result. The bits vacated by the operation are filled with 0. Syntax result <<= expression result Any variable. expression The number of bits to move. Examples. Using the <<= operator is the same as specifying result = result << expression

  8. Left Shift

    The << operator is overloaded for two types of operands: number and BigInt.For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt left shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number left shift.

  9. JavaScript left shift operator assignment

    The Bitwise left shift operator (<<) takes the two numbers and left shift the bits of first operand by number of place specified by second operand. For example: for left shifting the bits of x by y places, the expression ( x<<y) can be used. It is equivalent to multiplying x by 2y. The example below describes how left shift operator works: 1000 ...

  10. How does the Javascript left shift operator work?

    The control of whatever an integer is negative or positive is done by setting the signal bit, the bit of highest relevance in the 32-bits chain (2^31). If 0 its positive, if 1 its negative. So it happens that 4030011392 is bigger than 2147483647 and it means the signal bit was "accidentally" set to 1 in the process, causing the number to become ...

  11. Demystifying JavaScript Operators: What Does That Symbol Mean?

    The assignment operator in JavaScript is used to assign values to variables. It is represented by the "=" symbol. For example, if you have a variable named "x" and you want to assign the ...

  12. Left Shift Assignment Operator (<<=)

    The <<= operator shifts the bits of result left by the number of bits specified in expression. For example: temp = 14. temp <<= 2. document.write (temp); To run the code above, paste it into JavaScript Editor, and click the Execute button. The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56 ...

  13. Left Shift ( ) Bitwise Operator in JavaScript

    The Left Shift Assignment Operator is represented by "<<=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number. This can also be explained as

  14. JavaScript Assignment Operators

    The Left Shift Assignment Operator is represented by "<<=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number. This can also be explained as

  15. Javascript Assignment Operators (with Examples)

    Addition assignment operator. The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand. On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

  16. Left shift (<<)

    The << operator is overloaded for two types of operands: number and BigInt.For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt left shift if both operands become BigInts; otherwise, it converts both operands to 32-bit integers and performs number left shift.

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

  18. JavaScript Unsigned Right Shift Assignment Operator

    In JavaScript ">>>=" is known as the unsigned right shift assignment bitwise operator. This operator is used to move a particular amount of bits to the right and returns a number that is assigned to a variable. Syntax: a >>>= b. Meaning: a = a >>> b. Return value: It returns the number after shifting of bits.

  19. What is the JavaScript >>> operator and how do you use it?

    15. >>> is the unsigned right shift operator ( see p. 76 of the JavaScript 1.5 specification ), as opposed to the >>, the signed right shift operator. >>> changes the results of shifting negative numbers because it does not preserve the sign bit when shifting.

  20. What does a bitwise shift (left or right) do and what is it used for?

    The bit shift operators are more efficient as compared to the / or * operators. In computer architecture, divide(/) or multiply(*) take more than one time unit and register to compute result, while, bit shift operator, is just one one register and one time unit computation.

  21. Unsigned right shift (>>>)

    The unsigned right shift (>>>) operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes 0, so the resulting number is always positive.