
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
66 lines
1.8 KiB
Plaintext
66 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,javascript]
|
|
----
|
|
function f(){
|
|
i = 1; // Noncompliant; i is global
|
|
|
|
for (j = 0; j < array.length; j++) { // Noncompliant; j is global now too
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
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[]
|