1
function myFunc(trueOrFalse) {
   return trueOrFalse ? true : false
}

above function can be written as myFunc(trueOrFalse) => trueOrFalse but what if trueOrFalse is not present? that's why I wrote the first function explicitly return true or false in boolean.

Sharon Chai
  • 507
  • 1
  • 6
  • 20

3 Answers3

2

You can double negate that object.

Basically, it's used to convert a truthy - falsy value to a boolean. Reference

var myFunc = (trueOrFalse)=> !!trueOrFalse;

console.log(myFunc());
console.log(myFunc('hello'));
console.log(myFunc(true));
console.log(myFunc(false));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
2

Function arguments without assign are undefined which is a falsy value. So you can write:

function myFunc(trueOrFalse) {
   return trueOrFalse
}

Calling myFunc() will return undefined which is falsy. Just Beware that falsy is not equals to false:

if(false) {
    // it will not be executed
}

if(undefined){
    // it will not be executed
}

// but:
false == undefined // false

So depending your needs you'd want transform this to false, one approach could be using default parameters:

function myFunc(trueOrFalse = false) {
   return trueOrFalse
}

calling myFunc() now will return false, for example.

guijob
  • 4,413
  • 3
  • 20
  • 39
0

with EcmaScript6 you can set in the function parameters a default such as

function myFunc(trueOrFalse = false){
   return trueOrFalse ? true : false;
}

ECMASCRIPT6 and IE Not all aspects of EcmaScript6 are supported by IE 11 or lower, this means you will come into an issue if you set defaults in your function params

DataCure
  • 425
  • 2
  • 15