CodeSOD: Characters Remaining
Tina works for a major European government. During the height pandemic, her team needed to roll out many new sites to support remote, self-service interactions with government agencies.
On one of these sites, they needed to create a contact form. The contact form was one of those that applied a character limit to the message. This character limit meant that the code needed to check the length of the input string, and then compare that against some max characters, and then output the "characters remaining" in an output field.
function textCounter(theField,theCharCounter,maxChars){var strTemp = "";for (var i = 0; i < theField.value.length; i++){var strChar = theField.value.substring(i, i + 1);strTemp += strChar;}theCharCounter.value = maxChars - strTemp.length;};
theField is the textarea. theCharCounter is a read-only input field, where we store the output. And the for loop in the middle of this function is where we lose our minds.
They create a strTemp, and then for each character in the input, we grab a substring of that character and append it to strTemp. Then we compare strTemp.length against our maxChars to calculate the remaining characters.
In many cases, when I look at bad code, I can get a sense of how or why someone blundered down the path they're on, but this one is a real puzzler. They use the length to drive the for loop! They already understood what length is for. Are they worried about the value mutating while this function executes? If so, I've got bad news for them about how JavaScript runs in a browser context, and also, if that were the case, what is this supposed to do anyway?
They could have solved this problem easily, but instead they went to great lengths.
[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!