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 Node.js Basics 2017 Building a Command Line Application Parsing JSON

Aaron Smith
Aaron Smith
19,091 Points

const vs. var

Why are we using const to define all our variables instead of var? Is there an advantage to this or is it just convention when working with node.js?

Patrik Horváth
Patrik Horváth
11,110 Points

Cons cant be changed this is why :)

3 Answers

Team Treehouse's workshop on defining variables with let and const is very helpful with regards to their usage.

There is also an article by Mathias Bynens where he subjectively wrote:

  • use const by default
  • only use let if rebinding is needed.
  • (var shouldn't be used in ES6)

Here is the link to his article

Cheers! :)

Amrit Pandey
Amrit Pandey
17,595 Points

Well, the usage of const have nothing to do with where we use it. const is a variable declaration, which says that, any const variable once initialized cannot be mutated.

This means, once you assign any value to a variable, it cannot be further changed. So, lets say you created a variable to store your name, now your name should not change anytime in program by any means by user or end-user.

const myName = 'Amrit';

Now, there is a function that changes the value of myName variable.

function changeName(otherName){
  myName = otherName;

BUT, since your name is a constant(declared under const) and is immutable, function will fail to change the value of myName. In fact, compiler will throw an error.

This level of immutability is not achieved by var declaration. This is the reason, all the modern JavaScript code(ES6 and ES2015) use let and const to declare variables.