TOC

Good practice

👆 Back to top

Run safe

Ignore the error.

function getSafe(fn, defaultVal) {
  try {
    return fn();
  } catch (e) {
    return defaultVal;
  }
}

// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));

// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, "nothing"));

👆 Back to top

Differences

|| and ??

|| checks falsy values whearas ?? check null or undefined!

const a = 0 || 1; // 1
const b = 0 ?? 1; // 0
const c = false || 1; // 1
const d = false ?? 1; // false
const e = null || 1; // 1
const f = null ?? 1; // 1

contenteditable

+ select all texts

function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

var el = document.getElementById("foo");
selectElementContents(el);