# For loop not running through length

I can't figure out what I am doing wrong that is causing my for loop to not go through my length. I am trying to use a user input to convert a Binary to a Decimal, but its not working. What I have is

Edited

``````var val = \$("txtIn").value;
if (cT[1].checked) {
var bVal = val;
if (isNaN(bVal)) {
alert(val + " is not a number. A number is required to run the program.");
} else if ((val % 1) !== 0) {
alert(val + " is not an integer. A whole number is required to run the program.");
} else if (bVal < 0) {
alert(val + " is not able to convert. Input must be positive integer.");
} else {
convertByArrayB(bVal);
}
}

function convertByArrayB(bVal) {
var r, i, j;

for (i = 0; i < bVal.length; i++) {
r = bVal.charAt(i);
if (r !== '1' && r !== '0') {
}

var nv = parseInt(r, 2);

}

\$("txtOut").value = nv;

}``````

I don't think you need the top portion, but better safe than sorry. Thank you in advance for any help. (Love this community BTW)

## 1 Answers For loop not running through length

You're changing `bVal` inside the loop when you do:

``````bVal = nv;
``````

so the value of `bVal.length` is `undefined` on the next iteration, and the loop stops.

The code that calls `parseInt()` should be after the loop, not inside it. There's no need to reassign `bVal`, and it should parse `bVal`, not `r[i]`.

``````function convertByArrayB(bVal) {
var r, i, j;

for (i = 0; i < bVal.length; i++) {
r = bVal.charAt(i);
if (r !== '1' && r !== '0') {
return;
}
}
var nv = parseInt(bVal, 2);

document.getElementById("txtOut").value = nv;

}

convertByArrayB("101");``````
``````<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Result: <input id="txtOut">``````