0

looking to see if a shorthand for something I do quite commonly exists.

I commonly write/use functions that will return false if unable to do what they're able to do, but an object if they can. I also might commonly want to check if was successful.

Eg.

function someFunc() {
    // assume a is some object containing objects with or without key b
    // edit: and that a[b] is not going to *want* to be false
    function getAB(a, b) {
        if(a[b]) return a[b];
        return false;
    }

    let ab = getAB(a, b);
    if(!ab) return false;
}

I just wanted to know if there was some kind of shorthand for this. Eg, in fantasy land,

//...
let ab = getAB(a, b) || return false
//...
Sam Clarke
  • 120
  • 1
  • 11

1 Answers1

1

You can use or operator like:

return a[b] || false

Your full example code can be written as:

function someFunc() {
    // assume a is some object containing objects with or without key b
    function getAB(a, b) {
      return a[b] || false
    }

    return getAB(a, b); // getAB already returns the value, no need to check again.
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231