2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
Any variable or function declared in the global scope implicitly becomes attached to the global object (the ``++window++`` object in a browser environment). To make it explicit this variable or function should be a property of ``++window++``. When it is meant to be used just locally, it should be declared with the ``++const++`` or ``++let++`` keywords (since ECMAScript 2015) or within an Immediately-Invoked Function Expression (IIFE).
This rule should not be activated when modules are used.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
var myVar = 42; // Noncompliant
function myFunc() { } // Noncompliant
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
window.myVar = 42;
window.myFunc = function() { };
----
or
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
let myVar = 42;
let myFunc = function() { }
----
or
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
// IIFE
(function() {
var myVar = 42;
function myFunc() { }
})();
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Define this declaration in a local scope or bind explicitly the property to the global object.
=== Highlighting
variable or function
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== relates to: S806
=== relates to: S2703
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]