Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 981
jrode Avatar asked Jun 20 '14 17:06

jrode


Video Answer


1 Answers

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
like image 182
bhaskaraspb Avatar answered Oct 10 '22 15:10

bhaskaraspb