Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "|" (single pipe) do in JavaScript?

Tags:

javascript

People also ask

What is single pipe?

one-pipe system means a system of piping between sanitary fixtures and a drain in which both waste and soil water are permitted to flow down a common stack.

What is single pipe and double pipe?

Modern homes tend to have a single-pipe system which involves one vertical large-diameter pipe (called a soil stack) running inside the property. In older more traditional homes, it involves a dual-pipe setup. Wastewater and soil water are taken separately to the public sewer system.

What do double pipes mean in JavaScript?

The double pipe operator ( || ) is the logical OR operator . In most languages it works the following way: If the first value is false , it checks the second value. If that's true , it returns true and if the second value is false , it returns false .

What does pipe do in TypeScript?

A pipe is a function or operator that allows us to pass the output of a function as the input of another. JavaScript and TypeScript don't support pipes natively (as an operator), but we can implement our pipes using the following function: const pipe = <T>(... fns: Array<(arg: T) => T>) => (value: T) => fns.


This is a bitwise or.
Since bitwise operations only make sense on integers, 0.5 is truncated.

x | 0 is x, if x is an integer.


Bit comparison is so simple it's almost incomprehensible ;) Check out this "nybble"

   8 4 2 1
   -------
   0 1 1 0 = 6  (4 + 2)
   1 0 1 0 = 10 (8 + 2)
   =======
   1 1 1 0 = 14 (8 + 4 + 2)

Bitwise ORing 6 and 10 will give you 14:

   alert(6 | 10); // should show 14

Terribly confusing!


A single pipe is a bit-wise OR.

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1.

JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0.


This example will help you.

var testPipe = function(input) { 
   console.log('input => ' + input);
   console.log('single pipe | => ' + (input | 'fallback'));
   console.log('double pipe || => ' + (input || 'fallback'));
   console.log('-------------------------');
};

testPipe();
testPipe('something'); 
testPipe(50);
testPipe(0);
testPipe(-1);
testPipe(true);
testPipe(false);