DEV Community

Discussion on: IIFE's (Immediately-Invoked Function Expressions) in JavaScript Explained in 3 Minutes

Collapse
 
gaberomualdo profile image
Gabe Romualdo • Edited

While it can be useful to not have any variables declared on the global scope entirely, variable naming collisions should, to the best of my knowledge, only occur if a global variable has a value assigned to it. Thus, use strict prevents these collisions by preventing the assignment of variables in the global scope.

This is what I meant when I wrote “use strict to prevent the use of global variables”.

— Gabriel

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Oh really? I have assigned script-level variables the initial value of undefined with the intent of initializing them fully inside a later function call, in strict mode, which works just fine. To minimize the opportunity for conflicts, any function-scope variables use one of the ES5 keywords for this purpose in their declarations. Combined with a linter enforcing the rules, I make it as easy as possible to avoid trouble and detect the cause if it happens anyway.

Collapse
 
mathieuhuot profile image
Mathieu Huot

Hi Fred, I think your article is very well written and it made me review my knowledge about JavaScript strict mode, so thank you for that! Now, it might just be a wording thing but I wanted to clarify that use strict will not prevent the assignment of variables in the global scope, it will only prevent the assignment of undeclared variables.

'use strict';
//The assignment or reassignment of a declared variable will not throw an error.
let globalVariable = 'global value';
globalVariable = 'another value';
//This code will not throw an error.
Enter fullscreen mode Exit fullscreen mode
'use strict';
globalVariable = 'global value';
//This will throw -> ReferenceError: assignment to undeclared variable globalVariable
//Note that if you remove "use strict" it will not throw an error but create a global variable instead.
Enter fullscreen mode Exit fullscreen mode

Here's a reference to what I'm describing in the code block above : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Erreurs/Undeclared_var?utm_source=mozilla&utm_medium=firefox-console-errors&utm_campaign=default

You're right that because use strict is preventing the accidental creation of global variables, it reduces the risk of name collision although it doesn't prevent the assignment of a declared variable, global or not. Again, thank you for the learning opportunity!