-2

<p id="Test1"></p>
<p id="Test2"></p>
<p id="Test3"></p>

<script>
    {
        let v;
        v = 10;
    }

    let g = 20;

    var h = 15;

    document.getElementById('Test1').innerHTML = v;
    document.getElementById('Test2').innerHTML = g;
    document.getElementById('Test3').innerHTML = h;
</script>

As far as I learned, the let declared variables, can't be used outside a blocked scope, but if I run the code above, none of the 3 get shown? why is that? the scope ended there right?

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 2
    It throws an error because `v` is not defined, precisely because it is block scoped. (if you put update with `v` last you'll see `g` and `h` updated before the error is thrown) – pilchard Jun 06 '22 at 00:29

1 Answers1

0

When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message. **So here as soon as compiler try to show "v" js compiler throw error **

  • Uncaught ReferenceError: v is not defined And it terminate execution due to which you can not see that value of g and , h. here are two case: ** case 1** As "v" is commented you can see value of g and h(without error in console).
    let g = 20;
    
    var h = 15; {
    
      let v;
      v = 10;
    }
    
    
    //document.getElementById('Test1').innerHTML = v;
    document.getElementById('Test2').innerHTML = g;
    document.getElementById('Test3').innerHTML = h;
    <p id="Test1"></p>
    <p id="Test2"></p>
    <p id="Test3"></p>

** CASE 2** ** I tried to access v value as last so now you can see value of g and h as it was executed earlier before the error thrown by compiler.

let g = 20;

var h = 15; {

  let v;
  v = 10;
}



document.getElementById('Test2').innerHTML = g;
document.getElementById('Test3').innerHTML = h;
document.getElementById('Test1').innerHTML = v;
<p id="Test1"></p>
<p id="Test2"></p>
<p id="Test3"></p>

JavaScript is a single-threaded language, where only one command executes at a time. It has a Synchronous model of execution, where each line is executed line by line, top to bottom.

Unit and unless there is come function such as set timeout or asynchronized function. which execues differently.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Nexo
  • 2,125
  • 2
  • 10
  • 20