0

What is the best way to determine if a Javascript boolean is set? Here's an example of what I've been doing. It seems a bit excessive but I need to determine if a value is actually set, not just if it's true:

function doSomething (params, defaults) {

    params = params || {};
    defaults = defaults || {};

    var required = (params.required === true || params.required === false) 
        ? params.required
        : (defaults.required === true || defaults.required === false)
            ? defaults.required
            : true;

    if (required) {
        // perform logic
    }
}
G. Deward
  • 1,542
  • 3
  • 17
  • 30

3 Answers3

2

If a value hasn't been set that means it's undefined.

function printStuff(params) {
  if (params.hello !== undefined) {
    console.log(params.hello);
  } else {
    console.log('Hello, ');
  }
}

printStuff({ });
printStuff({
  hello: 'World'
});

To further drive the point home, here's how it can be used with booleans.

function schrodinger(params) {
  if (params.dead === undefined) {
    console.log('The cat is neither dead nor alive');
  } else if (params.dead) {
    console.log('The cat is dead');
  } else if (!params.dead) {
    console.log('The cat is alive');
  }
}

schrodinger({
  // Not specified
});

schrodinger({
  dead: true
});

schrodinger({
  dead: false
});
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
2

If you want to check whether an object has a specific property, that's the in keyword:

'required' in params

There's also the hasOwnProperty method, if you need to exclude properties inherited from a prototype (you probably don't for this case):

params.hasOwnProperty('required')
user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Would this solve your problem?

if(required!=undefined)
nrylee
  • 96
  • 7