Course: JavaScript

Progress (0%)

Exercise: Bitwise NOT

Exercise 14 Very easy

Prerequisites for the exercise

  1. JavaScript Strings Basics
  2. All previous chapters


Create a function to perform the NOT binary operation on a binary string.


Computers, as we all know, operate on binary numbers — numbers whose every single digit is either a 0 or a 1; hence the name 'binary'.

From the circuitry of the processor, to the input and output from I/O devices, to the wireless signals transmitted back and forth to the involved machinery, everything in the world of computers works on these magical numbers.

Typically numerous operations are performed on binary numbers. Amongst the most common is the NOT operation, sometimes comprehensively referred to as the bitwise NOT, or the bitwise complement operation.

The operation proceeds as follows: each bit in the binary number is inverted. That is, if it is 0, it's made 1; and similarly if it's 1, it's made 0.

In this exercise, you ought to create a function not() that takes as input a binary number in the form of a string (such as '10100') and then returns back its value after performing the bitwise NOT operation on it, once again in the form of a string.

If an empty string is given, the function should return back '' as well.

Below shown are some examples of the usage of this function:

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-14-Bitwise-NOT and put the .html solution files for this exercise within it.


To solve this problem, we just need to iterate over the given string and determine the inversion of each character one-by-one. If it's '0', we use '1', otherwise we use '0'.

Here's the solution:

function not(inputStr) {
   var outputStr = '';

   for (var i = 0; i < inputStr.length; i++) {
      if (inputStr[i] === '1') {
         outputStr += '0';
      else {
         outputStr += '1';
   return outputStr;

The variable outputStr is created to hold the NOT of the given binary string. At each iteration of the loop, the current character of the input binary string is inverted and then concatenated to outputStr to form the resulting string.

In the end, this very string is returned.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage