What Is the JavaScript ≫≫≫ Operator and How to Use It

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

It doesn't just convert non-Numbers to Number, it converts them to Numbers that can be expressed as 32-bit unsigned ints.

Although JavaScript's Numbers are double-precision floats(*), the bitwise operators (<<, >>, &, | and ~) are defined in terms of operations on 32-bit integers. Doing a bitwise operation converts the number to a 32-bit signed int, losing any fractions and higher-place bits than 32, before doing the calculation and then converting back to Number.

So doing a bitwise operation with no actual effect, like a rightward-shift of 0 bits >>0, is a quick way to round a number and ensure it is in the 32-bit int range. Additionally, the triple >>> operator, after doing its unsigned operation, converts the results of its calculation to Number as an unsigned integer rather than the signed integer the others do, so it can be used to convert negatives to the 32-bit-two's-complement version as a large Number. Using >>>0 ensures you've got an integer between 0 and 0xFFFFFFFF.

In this case this is useful because ECMAScript defines Array indexes in terms of 32 bit unsigned ints. So if you're trying to implement array.filter in a way that exactly duplicates what the ECMAScript Fifth Edition standard says, you would cast the number to 32-bit unsigned int like this.

(In reality there's little practical need for this as hopefully people aren't going to be setting array.length to 0.5, -1, 1e21 or 'LEMONS'. But this is JavaScript authors we're talking about, so you never know...)

Summary:

1>>>0            === 1
-1>>>0 === 0xFFFFFFFF -1>>0 === -1
1.7>>>0 === 1
0x100000002>>>0 === 2
1e21>>>0 === 0xDEA00000 1e21>>0 === -0x21600000
Infinity>>>0 === 0
NaN>>>0 === 0
null>>>0 === 0
'1'>>>0 === 1
'x'>>>0 === 0
Object>>>0 === 0

(*: well, they're defined as behaving like floats. It wouldn't surprise me if some JavaScript engine actually used ints when it could, for performance reasons. But that would be an implementation detail you wouldn't get to take any advantage of.)

What is operator in JS?

>>> is a right shift without sign extension

If you use the >> operator on a negative number, the result will also be negative because the original sign bit is copied into all of the new bits. With >>> a zero will be copied in instead.

In this particular case it's just being used as a way to restrict the length field to an unsigned 31 bit integer, or in other words to "cast" Javascript's native IEEE754 "double" number into an integer.

What do and mean in Javascript?

These are the shift right (with sign) and shift left operators.

Essentially, these operators are used to manipulate values at BIT-level.

They are typically used along with the the & (bitwise AND) and | (bitwise OR) operators and in association with masks values such as the 0x7F and similar immediate values found the question's snippet.

The snippet in question uses these operators to "parse" the three components of a 32 bits float value (sign, exponent and fraction).

For example, in the question's snippet:

1 - (2*(b1 >> 7)) produces the integer value 1 or -1 depending if the bit 7 (the 8th bit from the right) in the b1 variable is zero or one respectively.

This idiom can be explained as follow.

  • at the start, b1, expressed as bits is 0000000000000000abcdefgh
    note how all the bits on the left are zeros, this comes from the

    b1 = data.charCodeAt(offset) & 0xFF assignement a few lines above, which essentially zero-ed all the bits in b1 except for the rightmot 8 bits (0xFF mask).

    a, b, c... thru h represent unknown boolean values either 0 or 1.

    We are interested in testing the value of a.
  • b1 >> 7 shifts this value to the right by 7 bits, leaving

    b1 as 00000000000000000000000a which, read as an integer will have value 1 or 0
  • this 1 or 0 integer value is then multiplied by 2

    it is then either 2 or 0, respectively.
  • this value is then substracted from 1, leaving either -1 or 1.

Although useful to illustrate the way the bit-operators work, the above idiom could be replaced by something which tests the bit 7 more directly and assigns the sign variable more explicitly. Furthermore this approach does not require the initial masking of the leftmost bits in b1:

var sign
if (b1 & 0x80) // test bit 7 (0x80 is [00000000]10000000)
sign = -1;
else
sign = 1;

What does the | operator do in JavaScript?

The pipeline operator (|>) calls its second operand (which should be a function) and passes its first operand as an argument to it.

That is,

arg |> func

is equivalent to

func(arg)

Its goal is to make function chaining more readable.


As it is now (in 2021), it's a non-standard and experimental thing created by Mozilla that works only in Firefox by enabling it explicitly.

However, because of the usefulness of this feature, there are two competing proposals in TC39, that would each add a different flavor of this operator to the language.

The exact syntax and semantics is to be determined, but in the simplest cases they will be similar to what's described here.


In Mozilla's variant (and the similar F#-style proposal) the code translated to this case will look like this:

const max = (_ => Math.max(..._))(
Object.values({a: 1, b: 2, c: 3})
)

console.log(max) //3

Strange javascript operator: expr 0

Source: LINK

This is the zero-fill right shift
operator which shifts the binary
representation of the first operand to
the right by the number of places
specified by the second operand. Bits
shifted off to the right are discarded
and zeroes are added on to the left.
With a positive number you would get
the same result as with the
sign-propagating right shift operator,
but negative numbers lose their sign
becoming positive as in the next
example, which (assuming 'a' to be
-13) would return 1073741820:

Code:

result = a >>> b;

What is the difference between operator in Java and JavaScript?

Both are the logical right shift, but JavaScript has some weirdness in how it handles numbers. Normally numbers in JavaScript are floats, but the bitwise operations convert them to unsigned 32 bit integers. So even though the value looks like it shouldn't change, it converts the number to a 32 bit unsigned integer.

The value that you see 4294843840 is just the same bits as -123456, but interpreted as unsigned instead of signed.

JavaScript triple greater than

That's an unsigned right shift operator. Interestingly, it is the only bitwise operator that is unsigned in JavaScript.

The >>> operator shifts the bits of expression1 right by the number of
bits specified in expression2. Zeroes are filled in from the left.
Digits shifted off the right are discarded.

What is the double tilde (~~) operator in JavaScript?

That ~~ is a double NOT bitwise operator.

It is used as a faster substitute for Math.floor() for positive numbers. It does not return the same result as Math.floor() for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

  • How does the "this" keyword work?

var x = function() vs. function x()  —  Function declaration syntax

  • var functionName = function() {} vs function functionName() {}

(function(){})()  —  IIFE (Immediately Invoked Function Expression)

  • What is the purpose?, How is it called?
  • Why does (function(){…})(); work but function(){…}(); doesn't?
  • (function(){…})(); vs (function(){…}());
  • shorter alternatives:
    • !function(){…}(); - What does the exclamation mark do before the function?
    • +function(){…}(); - JavaScript plus sign in front of function expression
    • !function(){ }() vs (function(){ })(), ! vs leading semicolon
  • (function(window, undefined){…}(window));

someFunction()()  —  Functions which return other functions

  • Two sets of parentheses after function call

=>  —  Equal sign, greater than: arrow function expression syntax

  • What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

|>  —  Pipe, greater than: Pipeline operator

  • What does the "|>" operator do in JavaScript?

function*, yield, yield*  —  Star after function or yield: generator functions

  • What is "function*" in JavaScript?
  • What's the yield keyword in JavaScript?
  • Delegated yield (yield star, yield *) in generator functions

[], Array()  —  Square brackets: array notation

  • What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
  • What is array literal notation in javascript and when should you use it?

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value}  —  Curly brackets: object literal syntax (not to be confused with blocks)

  • What do curly braces in JavaScript mean?
  • Javascript object literal: what exactly is {a, b, c}?
  • What do square brackets around a property name in an object literal mean?
  • How does this object method definition work without the "function" keyword? (ES2015 Method definitions)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}`  —  Backticks, dollar sign with curly brackets: template literals

  • What does this `…${…}…` code from the node docs mean?
  • Usage of the backtick character (`) in JavaScript?
  • What is the purpose of template literals (backticks) following a function in ES6?

//  —  Slashes: regular expression literals

  • Meaning of javascript text between two slashes

$  —  Dollar sign in regex replace patterns: $$, $&, $`, $', $n

  • JavaScript replace() method dollar signs

()  —  Parentheses: grouping operator

  • MDN: Grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"]  —  Square brackets or dot: property accessors

  • JavaScript property access: dot notation vs. brackets?

?., ?.[], ?.()  —  Question mark, dot: optional chaining operator

  • Question mark after parameter
  • Null-safe property access (and conditional assignment) in ES6/2015
  • Optional Chaining in JavaScript
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

::  —  Double colon: bind operator

  • JavaScript double colon (bind operator)

new operator

  • What is the 'new' keyword in JavaScript?
  • What is "new.target"?

...iter  —  Three dots: spread syntax; rest parameters

  • (...rest) => {}  —  What is the meaning of “…args” (three dots) in a function definition?
  • fn(...args)  —  What is the meaning of “foo(…arg)” (three dots in a function call)?
  • [...iter]  —  javascript es6 array feature […data, 0] “spread operator”
  • {...props}  —  Javascript Property with three dots (…), What does the '…rest' stand for in this object destructuring?


Increment and decrement

++, --  —  Double plus or minus: pre- / post-increment / -decrement operators

  • ++someVariable vs someVariable++ in Javascript


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

  • What is the purpose of the delete operator in Javascript?

void operator

  • What does `void 0` mean?

+, -  —  Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

  • What does = +_ mean in JavaScript, Single plus operator in javascript
  • What's the significant use of unary plus and minus operators?
  • Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
  • Why does JavaScript handle the plus and minus operators between strings and numbers differently?

|, &, ^, ~  —  Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

  • What do these JavaScript bitwise operators do?
  • How to: The ~ operator?
  • Is there a & logical operator in Javascript
  • What does the "|" (single pipe) do in JavaScript?
  • What does the operator |= do in JavaScript?
  • What does the ^ (caret) symbol do in JavaScript?
  • Using bitwise OR 0 to floor a number, How does x|0 floor the number in JavaScript?
  • Why does ~1 equal -2?
  • What does ~~ ("double tilde") do in Javascript?
  • How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call? (also here and here)

%  —  Percent sign: remainder operator

  • What does % do in JavaScript?

&&, ||, !  —  Double ampersand, double pipe, exclamation point: logical operators

  • Logical operators in JavaScript — how do you use them?
  • Logical operator || in javascript, 0 stands for Boolean false?
  • What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?, JavaScript OR (||) variable assignment explanation, What does the construct x = x || y mean?
  • Javascript AND operator within assignment
  • What is "x && foo()"? (also here and here)
  • What is the !! (not not) operator in JavaScript?
  • What is an exclamation point in JavaScript?

??  —  Double question mark: nullish-coalescing operator

  • How is the nullish coalescing operator (??) different from the logical OR operator (||) in ECMAScript?
  • Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
  • Is there a "null coalescing" operator in JavaScript?

**  —  Double star: power operator (exponentiation)

  • x ** 2 is equivalent to Math.pow(x, 2)
  • Is the double asterisk ** a valid JavaScript operator?
  • MDN documentation


Equality operators

==, ===  —  Equal signs: equality operators

  • Which equals operator (== vs ===) should be used in JavaScript comparisons?
  • How does JS type coercion work?
  • In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so?
  • [] == ![] evaluates to true
  • Why does "undefined equals false" return false?
  • Why does !new Boolean(false) equals false in JavaScript?
  • Javascript 0 == '0'. Explain this example
  • Why false == "false" is false?

!=, !==  —  Exclamation point and equal signs: inequality operators

  • != vs. !==
  • What is the difference between != and !== operators in JavaScript?


Bit shift operators

<<, >>, >>>  —  Two or three angle brackets: bit shift operators

  • What do these JavaScript bitwise operators do?
  • Double more-than symbol in JavaScript
  • What is the JavaScript >>> operator and how do you use it?


Conditional operator

?:…  —  Question mark and colon: conditional (ternary) operator

  • Question mark and colon in JavaScript
  • Operator precedence with Javascript Ternary operator
  • How do you use the ? : (conditional) operator in JavaScript?


Assignment operators

=  —  Equal sign: assignment operator

  • What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)

This symbol is also used for default parameters or default values in a destructuring assignment:

  • what does (state = {}) => state means
  • What does ({"key": "value"} = {}) syntax mean inside a JavaScript function

%=  —  Percent equals: remainder assignment

  • Having Confusion with Modulo operator

+=  —  Plus equals: addition assignment operator

  • How does += (plus equal) work?

&&=, ||=, ??=  —  Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

  • What purpose do &&=, ||= and ??= serve?
  • Replace a value if null or undefined in JavaScript
  • Set a variable if undefined
  • Ruby’s ||= (or equals) in JavaScript?
  • Original proposal
  • Specification

<<=, >>=, >>>=, &=, ^=, |= — Double less than, double greater than, triple greater than, ampersand, caret, or pipe followed by equal sign: bitwise assignments

  • What do these JavaScript bitwise operators do?

Destructuring

  • of function parameters: Where can I get info on the object parameter syntax for JavaScript functions?
  • of arrays: Multiple assignment in javascript? What does [a,b,c] = [1, 2, 3]; mean?
  • of objects/imports: Javascript object bracket notation ({ Navigation } =) on left side of assign


Comma operator

,  —  Comma operator (not to be confused with the comma used in variable declarations)

  • What does a comma do in JavaScript expressions?
  • Comma operator returns first value instead of second in argument list?
  • When is the comma operator useful?


Control flow

{}  — Curly brackets: blocks (not to be confused with object literal syntax)

  • JavaScript curly braces with no function or json

Declarations

var, let, const  —  Declaring variables

  • What's the difference between using "let" and "var"?
  • Are there constants in JavaScript?
  • What is the temporal dead zone?
  • var a, b;  —  Comma used in variable declarations (not to be confused with the comma operator): JavaScript variable definition: Commas vs. Semicolons


Label

label:  —  Colon: labels

  • What does the JavaScript syntax foo: mean?
  • What does ':' (colon) do in JavaScript?


Other

123n  —  n after integer: BigInt

  • What does character 'n' after numeric literal mean in JavaScript?

#  —  Hash (number sign): Private methods or private fields

  • What does the # symbol do in JavaScript?

_  —  Underscore: separator in numeric literals

  • Javascript numeric separators?
  • Is there a Javascript equivalent to the Ruby syntax using underscores (e.g. 10_000 = 10000) to make larger integers human readable?

C# bitwise operator vs Javascript bitwise operator

In JavaScript you are doing a Unsigned right shift assignment with >>>.


To duplicate this in C# you will need to use >> but you must first cast the int.

int x = -100;
int y = (int)((uint)x >> 2);
Console.WriteLine(y);


Related Topics



Leave a reply



Submit