Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my boolean not evaluate correctly?

So, as the title says, my boolean does not evaluate correctly, here is my code:

var unindexed_frmVersionCtrl = $("#frmVersionCtrl").serializeArray();

    unindexed_frmVersionCtrl[unindexed_frmVersionCtrl.length] = { name: "versionControl", value: 0 };
    console.log(unindexed_frmVersionCtrl);


    let historyEntry = false;

    for (const [key, value] of Object.entries(unindexed_frmVersionCtrl)) {

        if (value.name == "versionControlBool") {
            historyEntry = value.value;
            console.log(historyEntry);
        }

        if (value.name == "versionControl") {
            console.log(historyEntry);
            if (historyEntry == true) {
                value.value = 1;
                console.log("lel");
            }
            else {
                console.log("false");
                value.value = 0;
            }
        }
    }

    console.log(unindexed_frmVersionCtrl);

here is the output:

historyEntry evaluates to true even when it is false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

historyEntry evaluates to true even when it is false. I don’t know what to do. No idea.
I am just starting out with javascript and I have never been this confused. Thanks.

EDIT: typo.

>Solution :

The problem is your historyEntry = value.value;, in this case value.value is a string, not a bool.

You can do historyEntry = (value.value == 'true');

Demo

var unindexed_frmVersionCtrl = [{
  "name": 'versionControlBool',
  value: 'true'
}, {
  "name": 'versionCount',
  value: '25'
}, {
  "name": 'versionControl',
  value: 0
}]

var historyEntry = false;

for (const [key, value] of Object.entries(unindexed_frmVersionCtrl)) {
  if (value.name == "versionControlBool") {
    historyEntry = (value.value == 'true');
    console.log("typeof value.value = " + typeof(value.value))
    console.log(historyEntry);
  }

  if (value.name == "versionControl") {
    console.log(historyEntry);
    if (historyEntry == true) {
      value.value = 1;
      console.log("lel");
    } else {
      console.log("false");
      value.value = 0;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading