DEV Community

Rakshambika
Rakshambika

Posted on

Operators in JavaScript Part-2

Bitwise Operator:

  • Bitwise operators in JavaScript treat their operands as a sequence of 32 bits (zeros and ones) instead of normal numbers, performing operations directly at the binary level.
  • Bitwise operators are used to perform operations on the individual bits of a number.
  • Computers represent numbers internally in binary form (0s and 1s). Bitwise operators work directly with these binary representations.
Operator Usage Description
Bitwise AND x & y 1 in each bit position for which the corresponding bits of both operands are 1.
Bitwise OR `x \ y`
Bitwise XOR x ^ y 0 in each bit position for which the corresponding bits are the same and 1 in each bit position for which the corresponding bits are different.
Bitwise NOT ~x Inverts all the bits of the operand.
Left Shift x << y Shifts x in binary representation y bits to the left, shifting in zeros from the right.
Right Shift x >> y Shifts x in binary representation y bits to the right, discarding bits shifted off.
Zero-fill Right Shift x >>> y Shifts x in binary representation y bits to the right, discarding bits shifted off and shifting in zeros from the left.

Example:

// Bitwise Operators
let a = 5;
let b = 3;

console.log(`Bitwise AND - ${a & b}`);
console.log(`Bitwise OR - ${a | b}`);
console.log(`Bitwise XOR - ${a ^ b}`);
console.log(`Bitwise NOT - ${~a}`);
console.log(`Left Shift - ${a << 1}`);
console.log(`Right Shift - ${a >> 1}`);
console.log(`Zero-fill Right Shift - ${a >>> 1}`);
Enter fullscreen mode Exit fullscreen mode

Output:


Conditional (Ternary) Operator:

  • This is the only JavaScript operator that takes 3 operands.
  • It assigns one of the two values to a variable based on some condition.
  • The ternary operator is a shorthand way of writing an if...else statement.

The syntax for this operator is:
condition? val1: val2;

If the condition is true, this operator returns val1; else it returns val2.

Example:

let age = 20;

let result = age >= 18 ? "Eligible to Vote" : "Not Eligible to Vote";

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:


String Operator:

  • Sometimes you need to join two or more strings together in JavaScript. Technically, joining two strings is known as string concatenation.
  • We use the concatenation operator (+) for this purpose.
  • This operator concatenates two or more strings together and returns a single string which is the union of all the operand strings.
  • Remember, you need at least one of the operands as strings otherwise + will act as an Arithmetic Operator.

Example:

let a = "Age: ";
let b = 21;

console.log(a + b);
Enter fullscreen mode Exit fullscreen mode

Output:


Top comments (0)