Reputation: 1973
I'm trying to understand this source code to learn how to make artblocks.
https://api.artblocks.io/generator/9000000
The code looks like this:
<script>
'use strict';
{
....
}
</script>
Why is the whole script in the HTML wrapped in curly braces? And why does the script still work?
Upvotes: 3
Views: 579
Reputation: 1168
In JavaScript, curly braces are used to create a new block. Curly braces were placed to make sure no code would conflict with the code inside and vice versa, make sure the code in the curly braces didn't affect some other code.
Upvotes: 1
Reputation: 371019
It's just a plain block.
Why is the whole script in the HTML wrapped in curly braces?
Presumably to avoid creating or interfering with global variables - like an IIFE. Otherwise, if the whole script was on the top level, it could cause problems with other scripts running on the same page.
For example, if there was
<script>
// script 1
const someElement = document.querySelector('.something');
</script>
<script>
// unrelated script 2
const someElement = document.querySelector('.somethingElse');
</script>
An error would be thrown, because both scripts are populating the top level with their variables. Putting standalone scripts into their own blocks significantly reduces the possibility of name collisions, hence
<script>
// script 1
{
const someElement = document.querySelector('.something');
// other code
}
</script>
That said, an IIFE is probably a better approach - it's much more common, more compatible, and doesn't have problems with function declarations.
<script>
// script 1
(function() {
const someElement = document.querySelector('.something');
// other code
})();
</script>
Upvotes: 2