Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
currentSortDirection()
that returns1
for an ascending sort,0
for a descending sort, and-1
for not set. Usingwhile (currentSortDirection() != desiredSortDirection) { sortColumn() }
works great, since-1 != true
and-1 != false
...but changing this towhile (Boolean(currentSortDirection) !== ...) {...}
forces-1
into atrue
, necessitating an additional couple of lines of prep, just to make jshint happy. – Droogans Nov 10 '13 at 17:56desiredSortDirection
is set toasc
? I know in a controlled environment you are probably in control over the valuedesiredSortDirection
is set to but in a shared environment when the input ofdesiredSortDirection
can come from anywhere in any form, type-checking against custom objects and defensive programming can save a lot of hours of debugging. Your code is absolutely fine and nothing is wrong with it, I'm merely pointing out that there is no one-fit-all answer/solution and it will always be scenario dependant. – François Wahl Apr 24 '14 at 16:19string=(string==String(string?true:false))?(string?true:false):(!string?true:false);
– Mark K Cowan Apr 16 '15 at 10:25function parseBool(val) { return val === true || val === "true" }
– WickyNilliams Sep 10 '15 at 14:24