Baz
Baz

Reputation: 13175

Explicit boolean conversion

I have a variable which is either set to something or is undefined. I wish to pass to a function true if the variable is defined else false. Here is the function:

function f(areRowsSelectable){...}

Which of the following would you do?

f(v);


f(v?true:false);

Or something else?

Upvotes: 3

Views: 1203

Answers (2)

Emil S. Jørgensen
Emil S. Jørgensen

Reputation: 6366

I would use the "typeOf" guard method.

It does not accept "truthy" arguments, so it depends on your function whether you can use it.

The tests are basically the same as czosel's answer, but his answer returns "truthy" while mine only accepts boolean true as true.

var tests = [
  //filled string
  'test',
  //empty string
  '',
  //Numeric empty
  0,
  //Numeric filled
  1,
  //Null
  null,
  //Completely undefined
  ,
  //undefined
  undefined,
  //Not-A-Number numeric value
  NaN,
  //Boolean true
  true
];
for (var t = 0; t < tests.length; t++) {
  var test = tests[t];
  var results = {
    test: test,
    isTruthy: !!test,
    isBoolTrue: (typeof test != "boolean" ? false : test),
    isDefined: (test !== void 0)
  };
  console.log(results);
}

EDIT 1

Since the question could be interpreted in several ways, i have included a couple of more tests.

  1. isTruthy matches czosel's answer. Registers truthy values like 1 as true.
  2. isBoolTrue was my first interpretation where it checks strictly whether a value is boolean true.
  3. isDefined simply returns if the variable contains anything at all.

Upvotes: 0

Christian Zosel
Christian Zosel

Reputation: 1424

I usually use double negation (which means applying the logical NOT operator twice) for explicit boolean conversion:

!!v

Examples:

!!'test' // true
!!'' // false
!!0 // false
!!1 // true
!!null // false
!!undefined // false
!!NaN // false

Alternatively, also Boolean(v) would work.

Upvotes: 3

Related Questions