ES6 - the use of var and let


in the start of the ES6 lesson it talks about using let rather than var to prevent overriding of values.
I was under the impression that the use of let was for local scope and that const was used to prevent values from being overridden?

The lesson text should be clearer, but the “override” they’re talking about pertains to redeclaration, specifically that let will not let you redeclare a variable in the same scope:

var a = 123
var a = "foo"   // redeclared, allowed with a var

let b = 234
let b = "bar"   // compile error

thank you with let do i also assume this would not also be permitted?

let a = 5;
a = 10;

I can also try testing in the console would be interested in the answer.

The let statement declares a block scope local variable, optionally initializing it to a value.

Variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks. In this way, let works very much like **var **. The main difference is that the scope of a var variable is the entire enclosing function:

function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  console.log(x);  // 2

function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  console.log(x);  // 1
1 Like

This is permitted, if you want this to not be permitted you need to use const

What is not permitted is

let a = 5;
let a = 10;

As in, you can’t declare again the same variable.