Variables conflicts in JavaScript

Suppose we have an index.html HTML page where you create a variable str in the script tag and display it on the screen:

<html> <head> <script> let str = 'script text'; alert(str); // shows 'script text' </script> </head> <body> ... </body> </html>

Suppose we also have a script.js file, which also sets the variable str:

let str = 'file text';

Now let our script.js file be linked to the index.html page as follows:

<html> <head> <script> let str = 'script text'; </script> <script src="script.js"></script> <script> alert(str); </script> </head> <body> ... </body> </html>

Since the variable str exists both in the index.html file and in the script.js file, there will be a conflict in which that variable will win, which is written below, that is, a variable from the script.js file. So our alert will output 'file text', not 'script text' as we expect.

The problem is actually very serious. In a real site, you will most often have several files with your scripts, in addition, you will use some third-party plugins. In this case, the variables and functions of one file may conflict with the variables and functions of another file.