36 lines
832 B
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
Variables declared with ``++var++`` have the special property that regardless of where they're declared in a function they "float" to the top of the function and are available for use even before they're declared. That makes scoping confusing, especially for new coders.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
To keep confusion to a minimum, ``++var++`` declarations should happen before they are used for the first time.
== Noncompliant Code Example
----
var x = 1;
function fun(){
alert(x); // Noncompliant as x is declared later in the same scope
if(something) {
var x = 42; // Declaration in function scope (not block scope!) shadows global variable
}
}
fun(); // Unexpectedly alerts "undefined" instead of "1"
----
== Compliant Solution
----
var x = 1;
function fun() {
print(x);
if (something) {
x = 42;
}
}
fun(); // Print "1"
----