Jump to content
Larry Ullman's Book Forums
Sign in to follow this  

Recommended Posts

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;





Share this post

Link to post
Share on other sites

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).

  • Upvote 1

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Create New...