Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  173] [ 5]  / answers: 1 / hits: 82590  / 11 Years ago, mon, november 11, 2013, 12:00:00

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();
}

More From » javascript

 Answers
60

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);

[#74358] Saturday, November 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erick

Total Points: 588
Total Questions: 92
Total Answers: 100

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;