Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript DOM Scripting By Example Adding and Removing Names Registering Names

Kevin Dunn
Kevin Dunn
6,623 Points

creating const inside of event handler

Why is it that Guil created the variables inside the event handler instead of creating all the variables together outside the event handler like so:

const form = document.getElementById('registrar');
const input = form.querySelector('input');
const text = input.value;
const ul = document.getElementById('invitedList');
const li = document.createElement('li');


form.addEventListener('submit', function(e){
  input.value = '';
  e.preventDefault();
  ul.appendChild(li);

});

is there much of a difference?

Kevin Dunn
Kevin Dunn
6,623 Points

I think I figured out why. Thanks

4 Answers

David Kanwisher
David Kanwisher
9,751 Points

If we were to assign the variable to the text input value OUTSIDE of the function (like in the example above) our variable will be empty string, since our input will always be blank on page load. Our event handler would always append an empty list item.

Ronald Lira
Ronald Lira
12,217 Points

Any idea why he used const instead of let inside the event handler?

thank you...

Roudy Antenor
Roudy Antenor
4,124 Points

Great question and great response -Thanks it helped me too!

I think he used const instead of let inside the event handler because the value is only set once per each submit event.