G. Deward
G. Deward

Reputation: 1592

Javascript ifDefined helper method?

Is there a helper method, or similar, in Javascript for isDefined? I just found this in a utility file I inherited:

'use strict';

var me = {
    ifDefined           : ifDefined,
    ifDef               : ifDefined,
    isDefined           : isDefined,
    isDef               : isDefined,
};

function isDefined (value) {
    return (typeof value != 'undefined');
}
function ifDefined (value, defaultValue) {
    return isDefined(value) ? defaultValue : value;
}

module.exports = me;

It appears the author is using it to have a shorthand method for the typeof check:

environment.u = isDef(envInfo.u, environment.u);
environment.x = isDef(envInfo.x, environment.x);
environment.s = isDef(envInfo.s, environment.s);

Upvotes: 0

Views: 283

Answers (3)

Fred Lackey
Fred Lackey

Reputation: 2391

There is not. If I had to do this, I wouldn't create a utility file for it. You could save just as much space in your code by using a shorthand variable and the ternary operator:

var udef = undefined;

environment.u = envInfo.u == udef ? environment.u : envInfo.u;
environment.x = envInfo.x == udef ? environment.x : envInfo.x;
environment.s = envInfo.s == udef ? environment.s : envInfo.s;

For comparison:

Upvotes: 1

Joe LeBeau
Joe LeBeau

Reputation: 26

What this function seems to do is check if a value is undefined, and if it is, returns a default value. Otherwise it returns the original value. The name is somewhat misleading, and I don't believe there is anything directly built in to JavaScript that mimics the functionality of your ifDefined function.

If what you are looking for is to simply check if something is defined or not, using typeof is unnecessary - you can simply compare against the global undefined object:

var x;
if(x !== undefined){
    console.log('this will not run');
}
else{
    console.log('this will run');
}

Some extra reading, if interested: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

Upvotes: 0

Bergi
Bergi

Reputation: 664971

Is there a helper method, or similar, in Javascript for isDefined?

No, there exists no builtin function for this.

Just using value !== undefined or value != null is short enough, it didn't warrant an extra utility function. The only native "typechecking" methods I am aware of are Array.isArray, isNaN and isFinite (and their Number.is… equivalents).

Upvotes: 2

Related Questions