Thursday, December 26, 2024
Google search engine
HomeLanguagesJavascriptXOR(^) Bitwise Operator in JavaScript

XOR(^) Bitwise Operator in JavaScript

In JavaScript, the bitwise XOR(^) Operator is used to compare two operands and return a new binary number which is 1 if both the bits in operators are different and 0 if both the bits in operads are the same. The operation is represented by the “|” symbol. This operator can be used to find the missing numbers in an array of natural numbers.

Let’s look at the truth table below to better understand the output of the XOR operation between two bits.

A B OUTPUT ( A ^ B )
0 0 0
0 1 1
1 0 1
1 1 0

Syntax: 

a ^ b

Example 1: In this example, we will perform the XOR operation on a Number.

Javascript




let a = 5;
let b = 4;
console.log(a^b);


Output:

1

Example 2: In this example, we will use the XOR operator to find missing the missing natural number in an array.

Javascript




function getMissingNo(a, n)
{
    let x1 = a[0];
    let x2 = 1;
    for (let i = 1; i < n; i++) x1 = x1 ^ a[i];
    for (let i = 2; i <= n + 1; i++) x2 = x2 ^ i;
  
    return x1 ^ x2;
}
let arr = [1, 2, 3, 5];
let N = arr.length;
let missingNo = getMissingNo(arr, N);
console.log(missingNo);


Output: When we XOR two equal numbers they cancel each other. Here we find the XOR of all elements up to a length of the array and then XOR the natural numbers up to that length. When we XOR both the result together they do not cancel as one number is missing. The missing number is returned after the XOR operation.

4

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

We have a complete list of JavaScript Bitwise Operators, to check those please go through, the JavaScript Bitwise Operators article

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments