66 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
JavaScript variable scope can be particularly difficult to understand and get right. The situation gets even worse when you consider the _accidental_ creation of global variables, which is what happens when you declare a variable inside a function or the ``++for++`` clause of a for-loop without using the ``++let++``, ``++const++`` or ``++var++`` keywords.
``++let++`` and ``++const++`` were introduced in ECMAScript 2015, and are now the preferred keywords for variable declaration.
=== 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
----
function f(){
i = 1; // Noncompliant; i is global
for (j = 0; j < array.length; j++) { // Noncompliant; j is global now too
// ...
}
}
----
=== 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
----
function f(){
var i = 1;
for (let j = 0; j < array.length; j++) {
// ...
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Add the "let", "const" or "var" keyword to this declaration of "{0}" to make it explicit.
'''
== Comments And Links
(visible only on this page)
=== is related to: S3798
=== on 13 Mar 2015, 13:49:55 Ann Campbell wrote:
I modified the code sample you provided, [~linda.martin]. Feel free to change it back.
=== on 13 Mar 2015, 14:02:49 Linda Martin wrote:
\[~ann.campbell.2] From the description it seems that each type you declare a variable without the keyword "var" it creates a global variable. Whereas it is only within for-loops and functions that that it creates a global variable.
Maybe it's my understanding of english that it's questionable or I wrongly expressed myself when I first described the rule ?
=== on 19 May 2015, 14:09:17 Linda Martin wrote:
Reviewed.
endif::env-github,rspecator-view[]