Skip to content

Instantly share code, notes, and snippets.

@jonaskahn
Last active March 6, 2023 11:30
Show Gist options
  • Save jonaskahn/41d10514b03087e9fb5eb734abb7e7c0 to your computer and use it in GitHub Desktop.
Save jonaskahn/41d10514b03087e9fb5eb734abb7e7c0 to your computer and use it in GitHub Desktop.

Style

  • Normal style:
result = (a !== null && a !== undefined) ? a : b;
  • Compact style:
result = a ?? b

The result of a ?? b is:

  • if a is defined, then a,
  • if a isn’t defined, then b.
  • The OR operator
result = a || b

Question

When a || b  equals to a ?? b

Ex:

let height = 0;

alert(height || 100); // 100
alert(height ?? 100); // 0

Precedence

let height = null;
let width = null;
let area1 = height ?? 100 * width ?? 50;
let area2 = (height ?? 100) * (width ?? 50);
let area3 = height ?? (100 * width) ?? 50;

@jonaskahn
Copy link
Author

Notice:

|| returns the first truthy value.
?? returns the first defined value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment