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 } } 
2
  • undefined would be a good guess. Commented Dec 22, 2016 at 19:39
  • Are you in use strict mode or just plain old javascript? :) Commented Dec 22, 2016 at 19:40

3 Answers 3

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 });

Sign up to request clarification or add additional context in comments.

Comments

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') 

Comments

0

Would this solve your problem?

if(required!=undefined) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.