JavaScript

JavaScript

Made by DeepSource

Restricted global variables being used JS-0122

Bug risk
Major

Ideally, JavaScript code should avoid using any variable names that are a property of popular JS execution environments. Doing so can (1) cause confusion when using variables that aren't defined anywhere, (2) make it easy to make mistakes while referring to the variable, thus introducing bugs, and (3) make the code harder to understand.

For instance, early Internet Explorer versions exposed the current DOM event as a global variable event, but using this variable has been considered as a bad practice for a long time. This issue ensures that similar global variables like name, event and fdescribe are not repeated as user declared variables.

Bad Practice

function handleEvent() {
    // The global `event` should not be used.
    if (event.target === submitButton) {
        // handle event
    }
}

Recommended

// `event` can be used as a variable or parameter name.
// Here, event is passed as an argument to the callback by the caller,
// like `onClick`.
function handleEvent(event) {
    if (event.target === submitButton) {
        // handle event
    }
}