0

Hello I am trying to see how let, var and const work in the following code :

console.log(a)
b()
var a = 'Hello World!';

function b() {
    var c = 'yo'
    console.log('entered b')
    console.log(a, c)
}

over here the program works fine for when 'a' is var but does not for 'let' and 'const'. I understand why it does so for 'const' as it's not been declared during initialization but why does 'let' not work and throw error similar to const about not being initialized. can't 'let' be declared without initialization similar to 'var'?

risky last
  • 385
  • 4
  • 12
  • You can't access variable declared with `let` _before_ its declaration has actually executed. Read: [Temporal Dead Zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz) – Yousaf Jul 12 '22 at 06:05
  • var means you can assign any data type and used especially when you dont know what would be the type during runtime, const means the values assigned once will not be change, let allows you to re-assign value but you cannot redeclare it, while with var you can redeclare and reassign values – Wajeeh Hasan Jul 12 '22 at 06:08
  • yes @Yousaf tysm for the reference link :D – risky last Jul 12 '22 at 06:11
  • I suggest reading about hoisting https://www.w3schools.com/js/js_hoisting.asp – omri_saadon Jul 12 '22 at 06:11

0 Answers0