why short-circuit JS?

1 min read


Dalam javascript Short-circuiting operators hanya mengevaluasi sisi kanan ekspresi jikadiperlukan.

contoh:

(A && B): B is only evaluated if A is true
(A || B): B is only evaluated if A is false
(A ?? B): B is only evaluated if A is null

contoh case :

// default values
a = a || 123; // assigns 123 to a if a is falsy
b = b ?? 123; // assigns 123 to b if b is nullish

// optional chaining with && ( .? is a modern alterative)
if (obj.m != null && obj.m() === '123') {
   // ...
}

// React: conditional rendering
return <>  
  {user != null &&
    <div>Welcome back, ${user.name}!</div>
  }
<>;

let a = 3;
let b = 3;
let c = 0;
let d = 0;

a &&= -Infinity;
b ||= -Infinity;
c &&= -Infinity;
d ||= -Infinity;

console.log(a); // -Infinity
console.log(b); // 3 (short-circuiting ||, because 3 is truthy)
console.log(c); // 0 (short-circuiting &&, because 0 is falsy)
console.log(d); // -Infinity

a = a && x; /* becomes */ a &&= x;
a = a || x; /* becomes */ a ||= x;
a = a ?? x; /* becomes */ a ??= x;
class C {
  constructor(name) {
    this.name = name;
  }

  get x() {
    return this._x;
  }

  set x(value) {
    console.log(`set ${this.name}.x to ${value}`);
    this._x = value;
  }
}

// nullish coalescing operator
const a = new C("a");
a.x = a.x ?? 3;
a.x = a.x ?? 4;
console.log(a.x)
// nullish assignment 
const b = new C("b");
b.x ??= 3;
b.x ??= 4;
console.log(b.x)
// output for nullish coalescing operator
"set a.x to 3"
"set a.x to 3"
3

Bima Sena

Leave a Reply

Your email address will not be published. Required fields are marked *