Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Bitwise AND

When a bitwise AND operation is performed on a pair of bits, it returns 1 only if both bits are 1.

Here’s a one-bit example:                                                                                                  

Operation

Result

0 & 0

0

0 & 1

0

1 & 0

0

1 & 1

1

 Here’s a 4-bit example:

JavaScript Bitwise OR

When a bitwise OR operation is applied to a pair of bits, it returns 1 if at least one of the bits is 1.

Here’s a one-bit example:

Operation

Result

0 | 0

0

0 | 1

1 | 0

1

1 | 1

1

4 bits example:

Operation

Result

1111 | 0000

1111

1111 | 0001

1111

1111 | 0010

1111

1111 | 0100

1111

JavaScript Bitwise XOR

When a bitwise XOR operation is applied to a pair of bits, it returns 1 if the bits are different.

Here’s a one-bit example:

Operation

Result

0 ^ 0

0

0 ^ 1

1 ^ 0

1

1 ^ 1

4 bits example:

Operation

Result

1111 ^ 0000

1111

1111 ^ 0001

1110

1111 ^ 0010

1101

1111 ^ 0100

1011

JavaScript Bitwise AND (&)

Bitwise AND returns 1 only when both bits are 1.

Decimal

Binary

5

00000000000000000000000000000101

1

00000000000000000000000000000001

5 & 1

00000000000000000000000000000001 (1)

Example

let x = 5 & 1;

JavaScript Bitwise OR (|)

Bitwise OR returns 1 if at least one of the bits is 1.

Decimal

Binary

5

00000000000000000000000000000101

1

00000000000000000000000000000001

5 | 1

00000000000000000000000000000101 (5)

Example

let x = 5 | 1;

JavaScript Bitwise XOR (^)

Bitwise XOR returns 1 when the bits are different.

Decimal

Binary

5

00000000000000000000000000000101

1

00000000000000000000000000000001

5 ^ 1

00000000000000000000000000000100 (4)

Example

let x = 5 ^ 1;

JavaScript Bitwise NOT (~)

Decimal

Binary

5

00000000000000000000000000000101

~5

11111111111111111111111111111010 (-6)

Example

let x = ~5;

JavaScript (Zero Fill) Bitwise Left Shift (<<)

This is a zero-fill left shift, where one or more zero bits are added from the right, causing the leftmost bits to drop off.

Decimal

Binary

5

00000000000000000000000000000101

5 << 1

00000000000000000000000000001010 (10)

Example

let x = 5 << 1;

JavaScript (Sign Preserving) Bitwise Right Shift (>>)

This is a sign-preserving right shift, where copies of the leftmost bit are added from the left, causing the rightmost bits to drop off.

Decimal

Binary

-5

11111111111111111111111111111011

-5 >> 1

11111111111111111111111111111101 (-3)

Example

let x = –5 >> 1;