Reputation: 100
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?
Upvotes: 0
Views: 129
Reputation: 943634
It doesn't matter if the function is anonymous or named. It doesn't matter if it is immediately invoked or not.
A function creates a new scope.
Your edit:
Note: this isn't exactly a question about scope.
It's entirely about scope. Using different scopes is how collisions are prevented.
A variable declared (with let
, const
or var
) inside a function is a different variable to one declared in a different function or outside of any function, even if it has the same name.
That said, this was how we handled scoping of variables in ES5.
In modern JavaScript we use either blocks or modules.
Modules have similar scoping rules to functions, and blocks are the scoping level for let
and const
.
{
let foo = 1;
document.write(foo);
}
{
let foo = 3;
document.write(foo);
}
Upvotes: 3