Explore Differences Between the var and let Keywords

Tell us what’s happening:

So the differences in let, const and var were the one thing about es6 that I thought I was somewhat familiar with going into this course. Having said that, the first lesson threw me for a loop as I initially understood it.

I browsed through the forum and think I figured it out, but just to clarify, “let” can’t be declared a second time but you can change its value later by simply saying “someLet = value” where as const can neither be declared a 2nd time nor can its value be changed?
Then of course “var” can be declared a 2nd time, “var someVar = value”, and thus overwritten entirely in this way. Sound correct?

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords

Yep, that’s spot on.

The rule that prevents you redeclaring let/const cuts down on programmer errors and should make the code a tiny bit faster (computer doesn’t have to do any extra work just in case a variable is redeclared in scope).

const cannot be reassigned, which is subtly different to just the value not being changed - for things like strings and numbers (primitives), yes, it means the value cannot change. But for objects (Objects, Arrays etc), the reference to the actual object assigned to const can’t change, but the values inside the object can (it’s still the same object though):

const foo = [1,2];
foo[0] = 100;  // this works
foo[1] = 200; // this works
foo = [1,2]; // this blows up

let and const are block level scope. So both are same with respect to scoping.

let x =6;
const y = 13;
{
 let x=5;
 const y = 10;
 console.log(x) // 5
 console.log(y) // 10
}
console.log(x) //6
console.log(y) //13

So where they differ? Answer is You can’t reassign const variable within scope.

{
  const x =13;
  x =45 // faill //TypeError: Assignment to constant variable.
}

Now come to var old way of declaring variable.
var is function level scoping.

var x = 23;
(function myFunc() {
   var x = 5;
   console.log('func',x);   //func 5
    {
     let x = 12;
     console.log('block',x); //block 12
    }
  console.log('after block',x); //after block 5
})()
console.log(x); // any guess?? // 23

Hope it help.

Go see MDN documentation :slight_smile: about let and const
I hope this doc will be helpfull to you :wink:

Ok, the way I first read it was that you couldn’t change the value of let after it had been declared, making it seem like const and let where redundant declarations. I understood the part about scope, I was just trying to clear up this one specific point. Think the mdn docs were the first source I read on the subject, the reason I thought to question my initial interpretation of the lesson to begin with.