Skip to content

Latest commit

 

History

History
100 lines (69 loc) · 2.78 KB

File metadata and controls

100 lines (69 loc) · 2.78 KB

Bitwise AND (&)

When every bit is 1, the result is 1, otherwise it is 0

    const a = 5;        // 00000000000000000000000000000101
    const b = 3;        // 00000000000000000000000000000011

    console.log(a & b); // 00000000000000000000000000000001
    // Expected output: 1

Bitwise OR (|)

When every bit is 0, the result is 0, otherwise it is 1

    const a = 5;        // 00000000000000000000000000000101
    const b = 3;        // 00000000000000000000000000000011

    console.log(a | b); // 00000000000000000000000000000111
    // Expected output: 7

Bitwise AND assignment (&=)

The bitwise AND assignment operator (&=) uses the binary representation of two operands, performs a bitwise AND operation on them, and assigns the result to the variable.

    let a = 5;      // 00000000000000000000000000000101
    a &= 3;         // 00000000000000000000000000000011

    console.log(a); // 00000000000000000000000000000001
    // Expected output: 1

Bitwise OR assignment (|=)

The bitwise OR assignment (|=) operator uses the binary representation of two operands, performs a bitwise OR operation on them, and assigns the result to the variable.

    let a = 5;      // 00000000000000000000000000000101
    a |= 3;         // 00000000000000000000000000000011

    console.log(a); // 00000000000000000000000000000111
    // Expected output: 7

Bitwise NOT (~)

Bitwise negation

    const a = 5;     // 00000000000000000000000000000101
    const b = -3;    // 11111111111111111111111111111101

    console.log(~a); // 11111111111111111111111111111010
    // Expected output: -6

    console.log(~b); // 00000000000000000000000000000010
    // Expected output: 2

Used in React to record side effect flags

Side effect flags can optimize performance, because in React, side effects (add, delete, modify) bubble up to the parent level. If the parent has no side effects, there's no need to traverse child nodes in depth-first order, saving performance

    //Define constants
    const Placement = 0b001; // 1
    const Update = 0b010;    // 2
    //Define operations
    let flags = 0b000; // 0
    //Add operation
    flags |= Placement;
    flags |= Update;
    console.log(flags.toString(2)); //0b011

    //Delete operation 0b011 & 0b110 => 0b010
    flags = flags & ~Placement;
    console.log(flags.toString(2)); //0b010
    console.log(flags); //2

    //Check if contains
    console.log((flags & Placement) === Placement);  // false
    console.log((flags & Update) === Update); // true

    //Check if not contains
    console.log((flags & Placement) === 0); // true
    console.log((flags & Update) === 0);  // fasle