ngplayground ngplayground - 11 days ago 5
Javascript Question

Javascript check if string if true or false and convert to Boolean

Is there a better way to improve the below statement to check if the

val()
is
'true'
or
'false'
and if it is then it will change it to a Boolean. The reason being, some of the values may be a word.

var thisval = $(this).val();
if (thisval == "true"){
ao[id] = true;
} else if (thisval == "false"){
ao[id] = false;
} else {
ao[id] = $(this).val();
}

Answer

Most readable:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : 
         thisval === 'false' ? false : 
         thisval;

One-liner based on the conditional operator:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : (thisval === 'false' ? false : thisval);

One-liner based on || and && behavior:

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval !== 'false') && thisval || false;

Shortest one-liner (combination of the above):

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval === 'false' ? false : thisval);