Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of variable declared by 'let' in a script tag

Consider following code snippet:

<script>
  let a = 1;
  console.log(a); //prints 1
</script>
<script>
  console.log(a); //prints 1
</script>

I want to ask if a is block scoped due to the declaration by let which means it is scoped to single <script> tag the why a in second script tag is printing value 1?

like image 750
a Learner Avatar asked Oct 23 '25 16:10

a Learner


1 Answers

If you want to restrict the scope of that a variable to the first <script> element, then wrap the content in a block statement:

<script> 
{
  let a=1; 
  console.log(a); //prints 1 
}
</script> 
<script> 
  console.log(a);  //Uncaught ReferenceError: a is not defined
</script> 
like image 116
Mads Hansen Avatar answered Oct 26 '25 09:10

Mads Hansen