Javascript Syntax - if statement - javascript

i have the following object:
var quarters = {
q1:false,
q2:false,
q3:false,
q4:{name: "i'm q4"}
}
My question is why the following IF is returning true?
if (quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false)
How can i ask if all quarters are false?
The reason I'm not using !quarters.q1 && !quarters.q2 && !quarters.q3 && !quarters.q4 is because sometimes, some of the properties are not defined at all.

why the following IF is returning true?
Assuming toppingOrder is quarters, lets fill it in and see what we have
if (toppingOrder.q1 == toppingOrder.q2 == toppingOrder.q3 == toppingOrder.q4 == false)
// same as
if (false == false == false == {name: "i'm q4"} == false)
// same as
if ((((false == false) == false) == {name: "i'm q4"}) == false)
// same as
if (((true == false) == {name: "i'm q4"}) == false)
// same as
if ((false == {name: "i'm q4"}) == false)
// same as
if (false == false)
// same as
if (true)
How can i ask if all quarters are false?
You either have to loop, use a logical AND && or some Array method like .every
// logical AND `&&`
if (
false === toppingOrder.q1
&& false === toppingOrder.q2
&& false === toppingOrder.q3
&& false === toppingOrder.q4
) // ...
// Array `.every`
if (
[toppingOrder.q1, toppingOrder.q2, toppingOrder.q3, toppingOrder.q4].every(
function (e) {return e === false;}
)
) // ...
It is actually much easier to test all true, so consider if you can phrase your if like that instead, e.g. using logical NOT !
if (!toppingOrder.q1 && !toppingOrder.q2 && !toppingOrder.q3 && !toppingOrder.q4) // ...
// or
if (
[!toppingOrder.q1, !toppingOrder.q2, !toppingOrder.q3, !toppingOrder.q4].every(Boolean)
) // ...

quarters.q1 == quarters.q2 == quarters.q3 == quarters.q4 == false
true == quarters.q3 == quarters.q4 == false
false == quarters.q4 == false
true == false
What you are essentially doing is this
everything will execute from left to right, unless you set the order (with ( ))
you could go this way about it
function get_bool(quarters){
for(k in quarters)
{
if(quarters[k] != false)
{
return true;
}
}
return false;
}

Related

Checking different codnitions for 2 array wheater its empty or not

I have two arrays say X and Y. I need to check conditions as below
if ((!x_array && x_array.length == 0) && (!y_array && y_array.length == 0)) {
console.log("======BOTH EMPTY======")
//display something
}
if ((x_array && x_array.length > 0) && (y_array && y_array.length > 0)) {
console.log("======BOTH NOT EMPTY======")
// do something
}
if ((x_array && x_array.length > 0) && (!y_array && y_array.length == 0)) {
console.log("======ONE IS EMPTY AND OTHER IS NOT======")
//do something
}
if ((!x_array && x_array.length == 0) && (y_array && y_array.length > 0)) {
console.log("======ONE IS EMPTY AND OTHER IS NOT======")
//do something
}
else {
//do something here
}
I checked with both OR and AND but nothing is working as needed. Please help
This code can't work. Let me point out the flaws for you.
!x_array && x_array.length == 0
This line can never evaluate to true if x_array is not defined or is null since null and undefined are "falsy" types. Because of that, false && true and false && false are never true. So, the first condition can't execute. A better way to write this would be:
...
if( ( !x_array ) || ( !y_array ) ) {
console.log( 'Either array is either undefined or null' );
}
Then, you can go on to check values by using the length property to see if they are defined but empty.
...
if( ( x_array.length === 0 ) || ( y_array.length === 0 ) ) {
console.log( 'Either array is empty' );
}
You can apply similar logic to find out the next few conditions for your code.
P.S.: It's a general stylistic preference to use camelCase in JavaScript. And try using the === operator when comparing values. The === can be rewritten as:
return ( typeof objA == typeof objB ) && ( objA == objB );
Since == only checks if values are equal and not the types.
The following is true: '2' == 2.
Why not simplify with some refactored code!
var isEmp = (input) => !input || input.length == 0;
And this use this as
if ( isEmp ( x_array ) && isEmp( y_array )
{
console.log( "both empty" );
}
else if ( !isEmp ( x_array ) && !isEmp( y_array )
{
console.log( "both not empty" );
}
else
{
console.log( "One of them is empty other is full" );
}
Or even simpler
var isXEmpty = isEmp( x_Array );
var isYEmpty = isEmp( y_Array );
var log = isXEmpty ? ( isYEmpty ? "Both Empty" : "Only X Empty" ) : ( isYEmpty ? "Only Y Empty" : "Both not Empty" );
Demo
console.log( "1", checkArrays( [], [] ));
console.log( "2", checkArrays( [1], [1] ));
console.log( "3", checkArrays( [1], [] ));
console.log( "4", checkArrays( [], [1] ));
function checkArrays( x_Array, y_Array )
{
var isEmp = (input) => !input || input.length == 0;
var isXEmpty = isEmp(x_Array);
var isYEmpty = isEmp(y_Array);
return isXEmpty ? (isYEmpty ? "Both Empty" : "Only X Empty") : (isYEmpty ? "Only Y Empty" : "Both not Empty");
}
the ! in the some of your conditions is the culprit;
I also merged two of your conditions to avoid repetition.
let x_array = ['1'];
let y_array = ['1'];
if ((x_array && x_array.length == 0) && (y_array && y_array.length == 0)) {
console.log("======BOTH EMPTY======")
//display something
}
if ((x_array && x_array.length > 0) && (y_array && y_array.length > 0)) {
console.log("======BOTH NOT EMPTY======")
// do something
}
if (((x_array && x_array.length > 0) && (y_array && y_array.length == 0)) || ((x_array && x_array.length == 0) && (y_array && y_array.length > 0))) {
console.log("======ONE IS EMPTY AND OTHER IS NOT======")
//do something
}
else {
//do something here
}

How can I write this javascript logic code into a more efficient/compact way? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
In a project I am working on I have 21 buttons that all have active and inactive states. The state of certain buttons is affected by other buttons being pressed as well as that button being pressed. In my html I use ng-click to call a function updateActiveButtons(num) to activate or deactivate certain buttons.
The best way I could think of was to use an array of 21 elements, all of which were set to false by default and then changed when they were pressed.
The problem is that my code is UGLY and I know that there has to be a much better way to logic it out.
Here is my updateActiveButtons function:
/* Array for active buttons
0: Company Name 1: Country 2: Industry 3: Search 4: Company Name - Seller Name 5: Company Name - Buyer Name 6: Country - USA 7: Country - China 8: Country - Israel
9: Country - Russia 10: Country - India 11: Country - Japan 12: Industry - Tech 13: Industry - Consumer 14: Industry - Pharma 15: Industry - Financial 16: Industry - Biotech 17: Industry - Industrial
18: Date 19: Valuation 20: Industry - Business
*/
$scope.activeButtonArray = new Array(21);
for (var i = 0; i < $scope.activeButtonArray.length; i++) { $scope.activeButtonArray[i] = false; }
//pos = position in array
$scope.updateActiveButtons = function(pos) {
console.log($scope.activeButtonArray[20]);
if(pos != 0 || pos != 1 || pos != 2 || pos != 3 || pos != 4 || pos != 5) {
$scope.activeButtonArray[pos] = !$scope.activeButtonArray[pos];
} else if(pos == 3 && !$scope.activeButtonArray[pos]) {
$scope.activeButtonArray[pos] = true;
} else if(pos == 3 && $scope.activeButtonArray[pos]) {
$scope.activeButtonArray[pos] = false;
}
if(pos == 18 || pos == 19) {
$scope.activeButtonArray[0] = false;
if($scope.activeButtonArray[6] == false && $scope.activeButtonArray[7] == false && $scope.activeButtonArray[8] == false && $scope.activeButtonArray[9] == false && $scope.activeButtonArray[10] == false && $scope.activeButtonArray[11] == false) {
$scope.activeButtonArray[1] = false;
}
if($scope.activeButtonArray[12] == false && $scope.activeButtonArray[13] == false && $scope.activeButtonArray[14] == false && $scope.activeButtonArray[15] == false && $scope.activeButtonArray[16] == false && $scope.activeButtonArray[17] == false && $scope.activeButtonArray[20] == false) {
$scope.activeButtonArray[2] = false;
}
}
if(pos == 0) {
$scope.activeButtonArray[0] = true;
if($scope.activeButtonArray[4] || $scope.activeButtonArray[5]) {
$scope.activeButtonArray[0] = true;
}
if($scope.activeButtonArray[6] == false && $scope.activeButtonArray[7] == false && $scope.activeButtonArray[8] == false && $scope.activeButtonArray[9] == false && $scope.activeButtonArray[10] == false && $scope.activeButtonArray[11] == false) {
$scope.activeButtonArray[1] = false;
}
if($scope.activeButtonArray[12] == false && $scope.activeButtonArray[13] == false && $scope.activeButtonArray[14] == false && $scope.activeButtonArray[15] == false && $scope.activeButtonArray[16] == false && $scope.activeButtonArray[17] == false && $scope.activeButtonArray[20] == false) {
$scope.activeButtonArray[2] = false;
}
if($scope.search.text == undefined || $scope.search.text == '') {
$scope.activeButtonArray[3] = false;
}
}
if(pos == 1) {
if($scope.activeButtonArray[4] == false && $scope.activeButtonArray[5] == false) {
$scope.activeButtonArray[0] = false;
}
if($scope.activeButtonArray[6] == true || $scope.activeButtonArray[7] == true || $scope.activeButtonArray[8] == true || $scope.activeButtonArray[9] == true || $scope.activeButtonArray[10] == true || $scope.activeButtonArray[11] == true) {
$scope.activeButtonArray[1] = true;
}
if($scope.activeButtonArray[12] == false && $scope.activeButtonArray[13] == false && $scope.activeButtonArray[14] == false && $scope.activeButtonArray[15] == false && $scope.activeButtonArray[16] == false && $scope.activeButtonArray[17] == false && $scope.activeButtonArray[20] == false) {
$scope.activeButtonArray[2] = false;
}
if($scope.search.text == undefined || $scope.search.text == '') {
$scope.activeButtonArray[3] = false;
}
}
if(pos == 2) {
if($scope.activeButtonArray[4] == false && $scope.activeButtonArray[5] == false) {
$scope.activeButtonArray[0] = false;
}
if($scope.activeButtonArray[6] == false && $scope.activeButtonArray[7] == false && $scope.activeButtonArray[8] == false && $scope.activeButtonArray[9] == false && $scope.activeButtonArray[10] == false && $scope.activeButtonArray[11] == false) {
$scope.activeButtonArray[1] = false;
}
if($scope.activeButtonArray[12] == true || $scope.activeButtonArray[13] == true || $scope.activeButtonArray[14] == true || $scope.activeButtonArray[15] == true || $scope.activeButtonArray[16] == true || $scope.activeButtonArray[17] == true || $scope.activeButtonArray[20] == true) {
$scope.activeButtonArray[2] = true;
}
if($scope.search.text == undefined || $scope.search.text == '') {
$scope.activeButtonArray[3] = false;
}
}
if(pos == 3) {
if($scope.activeButtonArray[4] == false && $scope.activeButtonArray[5] == false) {
$scope.activeButtonArray[0] = false;
}
if($scope.activeButtonArray[6] == false && $scope.activeButtonArray[7] == false && $scope.activeButtonArray[8] == false && $scope.activeButtonArray[9] == false && $scope.activeButtonArray[10] == false && $scope.activeButtonArray[11] == false) {
$scope.activeButtonArray[1] = false;
}
if($scope.activeButtonArray[12] == false && $scope.activeButtonArray[13] == false && $scope.activeButtonArray[14] == false && $scope.activeButtonArray[15] == false && $scope.activeButtonArray[16] == false && $scope.activeButtonArray[17] == false && $scope.activeButtonArray[20] == false) {
$scope.activeButtonArray[2] = false;
}
}
if(pos == 4) {
$scope.activeButtonArray[4] = true;
$scope.activeButtonArray[5] = false;
}
if(pos == 5) {
$scope.activeButtonArray[4] = false;
$scope.activeButtonArray[5] = true;
}
}
I have a lot of repeated code that comes out in a way that just doesn't feel very well done or professional. I wouldn't be proud to send this to a client. Does anyone have any suggestions as to how I could make this better?
On way would be to replace entire conditions (or blocks) by methods/functions
so
if($scope.activeButtonArray[4] || $scope.activeButtonArray[5]) {
$scope.activeButtonArray[0] = true;
}
becomes
if (somethingIsSomething($scope))
This has the added benefit of be much more self-documenting so you can "read" what you're doing.
I liked pixelearth's recommendation to just create another function so I did.
I decided to make a function that took an array, a start, and a end point as parameters and return true if any of the array values in that range are true.
Here is the function:
var arrayContainsTrue = function(arr, start, end) {
for(var i = start; i <= end; i++) {
if(arr[i] == true) {
return true;
}
}
return false;
}
and then to shorten my code I just did this (with different start and end points based on what was needed):
if(!arrayContainsTrue($scope.activeButtonArray, 6, 11))

Cannot read property '0' of undefined - javascript error?

I have a drop down menu, and when I select the 'All' option, it gives me this error on the console:
TypeError: Cannot read property '0' of undefined
at n.$scope.onSearchByChanged (http://localhost:8080/js/jenkinsVersion/directives/assignment-filter.js:70:81)
So, I went to my script, function, line 70,character 81 :
$scope.onSearchByChanged = function () {
if ($scope.filter.list.searchBy == 'DEPARTMENT_CODE' && !$scope.filterScope.departments) {
$scope.loadDepartments();
} else if ($scope.filter.list.searchBy != 'DEPARTMENT_CODE') {
$scope.filter.list.departmentId = 0;
}
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id; //line 70
}
$scope.clearFilter('text');
};
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
}
if ($scope.filter.list.searchBy == 'DEPARTMENT_CODE' && !$scope.filterScope.departments) {
$scope.loadDepartments();
}
$scope.isStatusSelected = function (status) {
return _.indexOf($scope.filter.list.talentAssignmentStatuses, status) > -1;
};
$scope.selectTalentAssignmentStatus = function (status) {
$scope.clearFilter('text');
if ($scope.isStatusSelected(status)) {
_.remove($scope.filter.list.talentAssignmentStatuses, function (el) {
return status == el;
});
} else {
$scope.filter.list.talentAssignmentStatuses.push(status);
}
};
here is the loadEditorGroups function :
$scope.loadEditorGroups = function () {
Reference.getEditorGroups($scope, function (response) {
$scope.filterScope.editorGroups = response.list;
if ($scope.filterScope.editorGroups.length > 0) {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id
}
});
};
I'm still learning JS. Why is this error being thrown? When I change the value of the item I want to retrieve from that editorGroups list it just gives me the same error but with the corresponding number. Your help would be appreciated, please let me know if I can supply further information. Thank you!
Your logic for this if-else block is probably wrong:
if ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id; //line 70
}
The program will enter the else if block when both:
the if condition is false, that is: ($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) == false
the else if condition is true, that is: ($scope.filter.list.searchBy != 'GROUP') == true
We can take these two statements and simplify them:
!($scope.filter.list.searchBy == 'GROUP' && !$scope.filterScope.editorGroups) && ($scope.filter.list.searchBy != 'GROUP')
($scope.filter.list.searchBy != 'GROUP' || $scope.filterScope.editorGroups) && ($scope.filter.list.searchBy != 'GROUP')
($scope.filter.list.searchBy != 'GROUP')
In step 2, I applied De Morgan's law to simplify !(A && B) to (!A || !B).
In step 3, I simplified the &&, since (A || B) && A is the same as just A.
So really, all we know when we enter the else if block is that searchBy != 'GROUP'. We do not know anything about editorGroups, and indeed, it may be undefined!
What you're probably looking for is:
if ($scope.filter.list.searchBy == 'GROUP' || !$scope.filterScope.editorGroups) {
$scope.loadEditorGroups();
} else if ($scope.filter.list.searchBy != 'GROUP') {
$scope.filter.list.groupId = $scope.filterScope.editorGroups[0].id;
}
Notice the || in the if condition. This ensures that the else if is executed only when ($scope.filter.list.searchBy != 'GROUP' && $scope.filterScope.editorGroups), so that editorGroups[0] will not give an error. I don't know enough if this is what you intended this code to do, so correct me when I'm wrong. :-)
70:81 means line 70, character 81.
The problem is at editorGroups[0]: If editorGroups is undefined, it cannot read editorGroups[0] because undefined has no property called 0.
Make sure that editorGroups isn't undefined and you'll be fine!

OR and AND conditions not returning as expected - What is best way to implement it?

I have an If statement that using || with an && operator e.g if((a || b) && c) however it is only works with the first condition i.e a but not with second i.e b even though running the debugger I can see that the condition is met and it goes to the correct line of code. Is there a better way to get this to work on both conditions?
code I have now:
function _getCatFormGUID(catName) {
debugger;
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if((catName == '1' && dept != "Entwicklung") || (catName == '7' && dept != "Entwicklung")) {
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
return "";}
I have tried the following also:
if((catName == '1' || catName == '7') && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
and
if(catName == '1' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
if(catName == '7' && dept == "Entwicklung"){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
It only returns for catName =='1'.
If I understood your problem correctly, I will write your first bit of code as bellow
function _getCatFormGUID(catName) {
var dept = Browser.getValue(getElement("126D81CA203C21CF014C8A3550227892FE4B4A6A"));
if (catName == '1' || catName == '7') {
if(dept == 'Entwicklung'){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
else{
return "8EDD0768A7CDF8FD8AE90DB473F41EF0B33FA14F";
}
}
else{
return "";
}
}
The problem is that you have to understand how those 2 logical operators do the comparison: because your first condition catName == '1' is true, it will never go to second conditions from the first parenthesis nor in the second paranthesis.Given your example, you might rewrite your logical condition from:
if((catName == '1' && dept == "Entwicklung") || (catName == '7' && dept == "Entwicklung")){
return "A270AE7F957A74EF0842403EEA0032017567F3E8";
}
to
if(dept == "Entwicklung" && catName == '1' || catName == '7'){ return something; }
}

JavaScript: Parsing a string Boolean value? [duplicate]

This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 4 years ago.
JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
Personally I think it's not good, that your function "hides" invalid values as false and - depending on your use cases - doesn't return true for "1".
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0" and "1".
(Maybe there is a way to compare only once against "true", but I couldn't think of something right now.)
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
Wood-eye be careful.
After looking at all this code, I feel obligated to post:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
return false;
if (typeof str === 'boolean')
{
if(str === true)
return true;
return false;
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
I shamelessly converted Apache Common's toBoolean to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {
if (str == "true") {
return true;
}
if (!str) {
return false;
}
switch (str.length) {
case 1: {
var ch0 = str.charAt(0);
if (ch0 == 'y' || ch0 == 'Y' ||
ch0 == 't' || ch0 == 'T' ||
ch0 == '1') {
return true;
}
if (ch0 == 'n' || ch0 == 'N' ||
ch0 == 'f' || ch0 == 'F' ||
ch0 == '0') {
return false;
}
break;
}
case 2: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N') ) {
return true;
}
if ((ch0 == 'n' || ch0 == 'N') &&
(ch1 == 'o' || ch1 == 'O') ) {
return false;
}
break;
}
case 3: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
if ((ch0 == 'y' || ch0 == 'Y') &&
(ch1 == 'e' || ch1 == 'E') &&
(ch2 == 's' || ch2 == 'S') ) {
return true;
}
if ((ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'f' || ch1 == 'F') &&
(ch2 == 'f' || ch2 == 'F') ) {
return false;
}
break;
}
case 4: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
if ((ch0 == 't' || ch0 == 'T') &&
(ch1 == 'r' || ch1 == 'R') &&
(ch2 == 'u' || ch2 == 'U') &&
(ch3 == 'e' || ch3 == 'E') ) {
return true;
}
break;
}
case 5: {
var ch0 = str.charAt(0);
var ch1 = str.charAt(1);
var ch2 = str.charAt(2);
var ch3 = str.charAt(3);
var ch4 = str.charAt(4);
if ((ch0 == 'f' || ch0 == 'F') &&
(ch1 == 'a' || ch1 == 'A') &&
(ch2 == 'l' || ch2 == 'L') &&
(ch3 == 's' || ch3 == 'S') &&
(ch4 == 'e' || ch4 == 'E') ) {
return false;
}
break;
}
default:
break;
}
return false;
}
console.log(toBoolean("yEs")); // true
console.log(toBoolean("yES")); // true
console.log(toBoolean("no")); // false
console.log(toBoolean("NO")); // false
console.log(toBoolean("on")); // true
console.log(toBoolean("oFf")); // false
Inspect this element, and view the console output.
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')

Categories