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

Can someone give an instance when the var keyword becomes problematic to use ?

As Andrew said in the video that sometimes using var keyword becomes problematic in javascript. However, I can't think of instance when it has become problematic. So can you please share the instance when you faced problem when declaring the variable with "var" keyword.

1 Answer

Steven Parker
Steven Parker
243,656 Points

Here's a good example.

This HTML and JavaScript code will display three buttons. Clicking any button will open an alert identifying the button by number.

But try replacing the let with var and you will find that all buttons report the button quantity instead of their individual number.

test.html
<button>Button 0</button> <button>Button 1</button> <button>Button 2</button>
test.js
var buttons = document.getElementsByTagName("button");

for (let i = 0; i < buttons.length; i++) {   // <- replace let with var on this line
  buttons[i].onclick = () => alert("Button " + i);
}