3

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?

2 Answers 2

3

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.

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

Comments

0

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.

1 Comment

"I wish to pass to a function true if the variable is defined else false" -> I think the OP actually asks for "truthy-conversion".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.