Where is variable scope documented

(Chrisvelevitch) #1

In this code:-

if (myTest)
     var myVar:Int = 1;
     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:
Did not find one about variable scope (ok that’s because 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) {
} else {

of even shorter

var myVar = if (myTest) 1 else 2;

(Allan Dowdeswell) #4

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

(Kevin Leung) #5

or even even shorter:
var myVar = myTest ? 1 : 2;

(Mark) #6

lol in that case I can even go shorter :stuck_out_tongue:

var m=myTest?1:2;

(Kevin Leung) #7

@mark.knol I just want to point out the EParenthesis expression is not necessary. Same for that in switch (o) {}.