JavaScript const area and curly braces

As I understand it, an area constis braces (a block). However, when I run the following code in a browser (FF), it gives no errors. Is the following JS code correct? Explain, please.

 <script type="text/javascript">
 {
     const Foo = "foo";        
 }
 </script>
 <div></div>
 <script type="text/javascript">
 {
     Foo = null;
 }
 </script>
+4
source share
2 answers

You will not get an error because

The code below says that you are using a constant variable Fooinside this code block, it const Foowill be available for the block bot

 {
     const Foo = "foo";        
 }

The code below says that you assign a variable Foowith a value nullthat will bind to the object window,

 {
    Foo = null;
 }

Foo = null;, window, const Foo='foo'

, Foo=null, window, , ,

  window.Foo

. , var, window,

+5

, const . :

<script type="text/javascript">
{
   const Foo = "foo";        
}
</script>
<div></div>
<script type="text/javascript">
{
   Foo = null;
}
</script>

:

{
   const Foo = "foo";        
}
{
   Foo = null;
}

Foo ( { }), Foo . A. Foo = null; : B. , . ,

  • Foo : - . Foo = "foo" A. .
  • Foo : - . .
  • Foo ( ): .

: . : const, let var. Foo=null . window.Foo, null.

, . Javascript - , "" . , , Foo . strict mode, . ( . MDN).

, , , .

<script type="text/javascript">
{
     const Foo = 'hello';
     Foo = 555; // success or fail ?
}
</script>

- . . : Foo .

<script type="text/javascript">
{
     const Foo = 'hello';
     {
        Foo = 555; // success or fail ?
     }
}
</script>

: . , (. ). Foo = 555; : B. B : A, Foo .

- :

<script type="text/javascript">
    {
        window.Foo = 'hello';
        {
            Foo = 555; // success or fail ?
        }
    }
</script>

? 🙂

...

. : :

{
  window.Foo = 'hello world';
  console.log('window.Foo?', window.Foo); // shows hello world
  {
    Foo = 555;
    console.log('window.Foo?', window.Foo); // shows 555
  }
}
Hide result

( ) . .

+2

Source: https://habr.com/ru/post/1694754/


All Articles