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 JavaScript Basics (Retired) Creating Reusable Code with Functions Variable Scope

Don't we use let instead of var now

As far as I know , var is no longer used and JS programmers use let and const for variables

Dehn Hunsworth
Dehn Hunsworth
7,189 Points

Yes you are correct. the Let and Const variables have more precise mechanisms and will avoid certain errors especially in loops. I have seen some still using Var in examples but as far as i know you would be better off using the new form of the variables and look more professional that way.

1 Answer

Dario Bahena
Dario Bahena
10,697 Points

const is for constants that is, variables who's values should not change. In more detail, when you assign a value to const, you cannot change its type and value later. However, if the const variable is set to an array or object, the contents within can be modified but the same variable cannot be changed to a different type.

let works similar to var except it is block scoped. example:

// this will not do what you expect it to do.
// this will print 0 - 9 one time
for (var i = 0; i < 10; i++) {
  console.log(i);
  for(var i = 0; i < 10; i++) {
    console.log(i);
  }
}
// this will behave correctly
// with will print 0 - 9 nine times. This is how most programming languages behave.
for (let i = 0; i < 10; i++) {
  console.log(i);
  for(let i = 0; i < 10; i++){
      console.log(i);
  }
}

Block scope is good. It mean that the variable declared within a block of code does not leak outside of that block.

If you are working with modern browsers, use let. If you are using older browsers, use var. If you are using a REPL console, var is convenient.