COMMUNITY

Where is variable scope documented


(Chrisvelevitch) #1

In this code:-

if (myTest)
{
     var myVar:Int = 1;
}
else
{
     myVar = 2;
}

the second reference to myVar is undefined.

This is due to myVar being only defined in the scope of the first block.

But where is this documented and what is it known as?


(Rudy Ges) #2

var myVar:Int = 1 and myVar = 2 are in two different blocks (and the later is not in a sub block of the former)

There is an entry in the manual about blocks: https://haxe.org/manual/expression-block.html
Did not find one about variable scope (ok that’s because https://haxe.org/manual/expression-var.html links to this entry for the “scoping behavior of local variables”).


(Mark) #3

“Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).”
somewhere on the internet

Haxe doesn’t have this variable hoisting, every block creates its own scope.


The following doesn’t answer the question at all, but you can also do this in Haxe:

var myVar = if (myTest) {
     1;
} else {
     2;
}

of even shorter

var myVar = if (myTest) 1 else 2;

(Allan Dowdeswell) #4

Or shorter still:
var myVar = (myTest) ? 1 : 2;