Difference between var and let

Hi, I have been started Javascript this week and my question is the following:

I don’t really get the difference between ‘var’ and ‘let’ because for me they pretty do the same thing. I did the following test

image

and what I did with var could have been done with ‘let’ as well.

So what is the big difference between the two of them.

Thank you !!! :slight_smile:

Hello, @system2553229654, and welcome to the forums!

The ‘big’ difference between var and let is scope. Variables declared with const and let have block scope. Variables declared with var have function scope. Consider the following trivial example:

const myFunction = () => {
  for(let i = 1; i <= 5; i++){
    const a = i * 10 // a has block scope
    let b = a * 10 // b has block scope
    var c = b * 10 // c has function scope
    console.log(`(Inside 'for' loop code block) a: ${a}  b: ${b}  c: ${c}`)
  } // a and b are not defined beyond this closing brace
  
  // console.log(`a: ${a}  b: ${b}  c: ${c}`) // ReferenceError: a is not defined 
  
  // console.log(`b: ${b}  c: ${c}`) // ReferenceError: b is not defined
  
  console.log(`\n(Outside 'for' loop code block, but still inside the function) c: ${c}`) // 5000
} // c is not defined beyond this closing brace

myFunction()

// console.log(`c: ${c}`) // ReferenceError: c is not defined

Output:

(Inside ‘for’ loop code block) a: 10 b: 100 c: 1000
(Inside ‘for’ loop code block) a: 20 b: 200 c: 2000
(Inside ‘for’ loop code block) a: 30 b: 300 c: 3000
(Inside ‘for’ loop code block) a: 40 b: 400 c: 4000
(Inside ‘for’ loop code block) a: 50 b: 500 c: 5000

(Outside ‘for’ loop code block, but still inside the function) c: 5000

If you copy the above code, and run it yourself, you can uncomment the commented out lines one at a time to see the errors thrown when trying to access a variable outside of its scope.

Thank you, I know understand better.

But at the 7th line you wrote as a comment ‘a and c are not defined beyond this closing brace’ isn’ It a and b rather than a and c ?

1 Like

Oops. Yes. I’ll fix that. Good eye!

1 Like

Perfect. Thank you for helping me so fast !!! :smiley:

1 Like