Christopher Bergin Posted December 17, 2012 Share Posted December 17, 2012 I'm wondering why variables that are declared at the beginning of a function are assigned the form elements and not their corresponding values. For instance... // Get a reference to the form elements: var type = document.getElementById('type'); var years = document.getElementById('years'); the program would then go on to check conditions... // Convert the year to a number: if (years && years.value) { years = parseInt(years.value, 10); } // Check for valid data: if (type && type.value && years && (years > 0) ) would the following revision be as efficacious? var type = document.getElementById('type').value; var years = document.getElementById('years').value; Chris Link to comment Share on other sites More sharing options...
HartleySan Posted December 17, 2012 Share Posted December 17, 2012 Your suggestion is not wrong, but also not recommended. By assigning a reference to a DOM element to a variable, you can first test whether the DOM element exists at all, which is a good idea. For example, if an element with the ID "years" does not exist, then trying to assign the value of such an element immediately to a variable will cause an error. Also, it never hurts to assign a DOM reference to a variable, as you never know if you'll need the DOM reference again (and searching through the DOM twice for the same element is a waste). 1 Link to comment Share on other sites More sharing options...
Christopher Bergin Posted December 17, 2012 Author Share Posted December 17, 2012 duly noted. Thanks for the response HartleySan. Chris Link to comment Share on other sites More sharing options...
Recommended Posts