Accidental Global Variables
Variables declared without any keyword (e.g. var, let, const ) are called Accidental global variables.
function fun(){
college = "Axis Colleges"; //Accidental global variable
}
This type of variable becomes a member of the window object.
function fun(){
college = "Axis Colleges"; //Accidental global variable
}
fun();
console.log(window.college) // Axis Colleges
Memory Leak
Creating variables like this leads to memory leaks. Since the scope of global variables never ends, they remain in memory throughout the execution of the javascript program even if they are not needed. that means the garbage collector never removes these variables from memory and it results in a memory leak.
Note: Garbage collector removes a variable or releases memory assigned to a variable when a variable scope ends.
How To Prevent This Memory Leak
Write your javascript code in strict mode to prevent this type of mistake. The strict mode was introduced in ECMAScript version 5. It enables you to write cleaner code and prevents you from writing less bug-prone code.
Activating Strict Mode
Strict mode is declared by adding "use strict"; to the begging of your code.
"use strict" is not a statement, it's an expression (to be precise it's just a string literal), therefore no browser will throw an error if it doesn't understand what it is.
"use strict" //Stric mode activated globally
college = "Axis Colleges" // This will cause an error
If we don't want to activate strict mode in the global scope, then we can also declare it inside the function, to activate strict mode only inside that particular function body.
function fun(){
"use strict";
college = "Axis College"; //This will cause an error
}
school = "SVM"; //This will not cause an error
fun();
Thank You For Reading! ♥
If you have any doubts or queries about this topic feel free to ask me in the comment section.
And if you find anything here which is not explained correctly, then also you can reach out to me.