Please explain let and const

Please explain let and const
0

#1

Please explain let and const. What the difference between let,const and var.
Add your examples. Thank you.


#2

https://m.youtube.com/results?q=let%20var%20const&sm=3


#3

var is function-scoped, meaning it’s visible in the function it was declared in.

function foo() {
  var a = 2;
  // This `a` is visible in this function only
}

function bar() {
  // The `a` in `foo` is not accessible here.
  // In fact, this function is not aware that the `a` in `foo` exists at all!
  
  var a = 'Hello';
  // This `a` is a different variable from that of `foo`.
  // They just happen to have the same name.
}

let and const are both block-scoped, meaning that they’re visible in the block they were declared in. Blocks are those parts of the code between { and } (such as if-blocks, loop blocks, and also functions. Note that objects are excluded here).

function foo() {
  if (...) {
    let a = 2;
    // This `a` is only visible in this if-block.
  }

  // We're now outside the if-block
  console.log(a);
  // will throw a `ReferenceError`
  // The `a` before is block-scoped, and is thus invisible outside that if-block.
}

let is useful in for-loop headers, because the variable we use in the for-loop will most likely only be needed in that for-loop anyway.

for (let i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

// `i` does not exist here!

const differs from let in that, you can’t reassign it a new value once you initialized it.

const a = 'hello'
a = 'hi' // you'll get an error if you do this!

Note the emphasis on reassign. If a is an object, you can still change its properties.

const a = { text: 'hello' };
a.text = 'hi' // valid!

Also note that when you use const, you should assign it a value immediately.

const a; // you can't do this!
a = 2;

That pretty much touches the basics of var, let and const. You can do a reading of YDKJS: Scope & Closures for a more in-depth discussion. The author explains it better than I do. :wink:


#4

Thank you so much. :slight_smile:


#5

Actually I’ve found your explanation really helpful - it sort of “consolidated” (or whatever) my first read of YDKJS.