Search code examples
javascriptlodashramda.js

Potentially undefined variable


I'm getting keys from global variable that is potentially not defined. Keys may not exist, too:

import { get } from 'lodash/fp';

const probablyGlobalFoo = typeof globalFoo === 'undefined' ? void 0 : globalFoo;

const baz = get('baz', probablyGlobalFoo) || get('bar.baz', probablyGlobalFoo) || 'baz';

typeof globalFoo === 'undefined' check is idiomatic to JavaScript but is clumsy and verbose. This case occurs a couple of times in my code base but not often enough to introduce another helper function to my utils library. I would prefer to just provide getter function instead that is handled properly, something like:

getFromAGetterAndCatchIfNotDefined('bar.baz', () => globalFoo);

Is there a straightforward way to handle this case with Lodash FP or Ramda APIs I'm missing?


Solution

  • If your global variable is defined on window (in the case of global var), you can check for window.globalFoo (or global.globalFoo in nodejs). If not you'll have to use the typeof check.

    To check for a property that doesn't exist in an object, or an undefined variable, you can use lodash/fp's getOr():

    const { getOr } = _;
    
    console.log(getOr('baz', 'bar.baz', window.globalFoo));
    
    const anotherValue = { bar: { baz: 5 } }
    
    console.log(getOr('baz', 'bar.baz', anotherValue));
    <script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)"></script>

    Or lodash's get():

    const { get } = _;
    
    console.log(get(window.globalFoo, 'bar.baz', 'baz'));
    
    const anotherValue = { bar: { baz: 5 } }
    
    console.log(get(anotherValue, 'bar.baz', 'baz'));
    <script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js)"></script>

    Or ramda's pathOr():

    const { pathOr } = R;
    
    console.log(pathOr('baz', ['bar','baz'], window.globalFoo));
    
    const anotherValue = { bar: { baz: 5 } }
    
    console.log(pathOr('baz', ['bar','baz'], anotherValue));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>