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

Natacha Romano
Natacha Romano
6,850 Points

I'm confused about var, let, const

I didn't understand the difference of var, let and const, i think it wasn't explained on the course, if anyone can explain it to my i really appreciate :)

2 Answers

Steven Parker
Steven Parker
229,644 Points

The "var" keyword declares variables in the scope of the current function, or with global scope outside of a function. But "let" declares variables in the scope of the current code block instead.

So, for example, when writing a conditional block inside a function, a variable declared with "var" would be available anywhere in the function. But a variable declared with "let" would only be available inside the conditional:

function test(x) {
  if (x > 0) {
    var vee = 1;
    let ell = 2;
    console.log(vee);  // 1
    console.log(ell);  // 2
  }
  console.log(vee);    // 1
  console.log(ell);    // ReferenceError: ell is not defined
}

test(1);
console.log(vee);      // ReferenceError: vee is not defined
console.log(ell);      // ReferenceError: ell is not defined

And "const" is just like "let" except that once it has been assigned, it cannot be assigned again.

And one other difference: anything declared with "var" is hoisted, but things declared with "let" or "const" are not.

Hi Natacha. The overly simple explanation would be that let and var are essentially the same, but let has become the new standard. Const is used when declaring a variable whose value will not change. There is a short course that covers these things as well as arrow function syntax and template literals. Here's a link.

https://teamtreehouse.com/library/getting-started-with-es2015-2

Hope this helps!