Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set boolean with default if options object does not exist

I want so set a boolean value I either get from a property in an options object, or if this is not defined want to set a default value.

const raw = options.rawOutput;

If options.rawOutput is not set, the default value should be true. Problem is: the options object may not exist at all.

Im looking for a more elegant solutions than something like this

if (options) {
  if (options.rawOutput) {
    raw = rawOutput;
  }
} else {
   raw = true;
}
like image 659
furtner Avatar asked Feb 24 '26 13:02

furtner


1 Answers

You could check if options exists and if the property rawOutput exists, then take that value, otherwise take true.

raw = options && 'rawOutput' in options ? options.rawOutput : true;

or the same but without conditional (ternary) operator ?:.

raw = !options || !('rawOutput' in options) || options.rawOutput;
like image 131
Nina Scholz Avatar answered Feb 27 '26 02:02

Nina Scholz