jrode
jrode

Reputation: 411

Set a default value for a boolean parameter in a javascript function

I have used typeof foo !== 'undefined' to test optional parameters in javascript functions, but if I want this value to be true or false every time, what is the simplest or quickest or most thorough way? It seems like it could be simpler than this:

function logBool(x) {
    x = typeof x !== 'undefined' && x ? true : false;
    console.log(x);
}

var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true

Upvotes: 10

Views: 11799

Answers (1)

bhaskaraspb
bhaskaraspb

Reputation: 326

You could skip the ternary, and evaluate the "not not x", e.g. !!x.

If x is undefined, !x is true, so !!x becomes false again. If x is true, !x is false so !!x is true.

function logBool(x) {
    x = !!x;
    console.log(x);
}

var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true

Upvotes: 31

Related Questions