Why you should care
with (document.forms["mainForm"].elements) { input1.value = "junk"; input2.value = "junk"; }
The problem is that the programmer has no way to verify that input1 or input2 are actually being resolved as properties of the form elements array. It is checked first for properties with these names, but if they aren’t found then it continues to search up the scope chain. Eventually, it reaches the global object where it tries to treat “input1” and “input2” as global variables and tries to set their “value” properties, which result in an error.
Instead, create a reference to the reused object and use it to resolve references.
How we detect
Bad Code
with (document.forms["mainForm"].elements) { input1.value = "junk"; input2.value = "junk"; }
Good Code
var elements = document.forms["mainForm"].elements; elements.input1.value = "junk"; elements.input2.value = "junk";
References
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.