Note: this isn't exactly a question about scope.
I'm reading a book that says that many people can add scripts to a web page, and for that reason, having global variables can cause naming collision. For example, say one person adds this script:
<script>
function showAreaOfWall(height, width) {
let area = height * width
return `<h1>Area: ${area}</h1>`
}
let message = showAreaOfWall(5, 20)
document.write(message)
</script>
The script above has a global variable called message
, which can't be declared again anywhere else. However, say someone does exactly that. Someone adds in another script that declares a variable with the same name.
<script>
function welcomeMessage(user) {
return `<h1>Welcome, ${user}!</h1>`
}
let message = welcomeMessage('Luke')
document.write(message)
</script>
As expected, we get an error:
Uncaught SyntaxError: Identifier 'message' has already been declared
Now my question is, how does an Anonymous Function or IIFE prevent this from happening?
This is how I'm thinking about it. Let's see what happens if both persons used IIFEs in their scripts:
<script>
document.write(function(height, width) {
let area = height * width
return `<h1>Area: ${area}</h1>`
}(5, 20))
</script>
<script>
document.write(function(user) {
return `<h1>Welcome ${user}!</h1>`
}('Luke'))
</script>
That one works perfectly. Cool. No name collisions. But it defeats the whole purpose of functions, because these functions aren't even reusable anymore, I'm not storing them anywhere...
Ok, those were IIFEs. But also, I can't wrap my head around how Anonymous Functions would prevent naming collisions. Both scripts can still assign an unnamed function to a variable with the same name.
How am I looking at this wrong?