I wasn't satisfied with the answer here, so like any normal person would do, I learned java byte code. Well, sort of... the rudimentary. So if anyone read this keep in mind that my findings have some extrapolations in them and could be inaccurate.. However it makes sens why it doesn't happen java (much less in javascript where my head was at when asking this) and it is ho so simple.
So now the byte code part:
here is what I got for this:
int a = 9;
System.out.println(a); // just here to prevent some optimization
if((a = 18) > 15){
System.out.println(a);
}
Code:
0: bipush 9
2: istore_1
// -- removed the System.out.print --
10: bipush 18
12: dup
13: istore_1
14: bipush 15
16: if_icmple 26
Here is what happens:
0: push 9 onto the stack
2: store it in the var a
10: push 18 onto stack
12: duplicate 18 on top of the stack
13: store it in var a
14 : push 15
16: the if statement if value1 is less than or equal to value2, branch to instruction at branchoffset.
So since the content of the condition is evaluated before the if statement itself, if we declared int a
in the condition, depending on where we define the scope of int a
to be, there would be scoping issues.
If it was inside the if block:
If we suppose int a would be scoped into the if block, it must still be evaluated before reaching it and thus being out of scope !
In other words:
while((int a = 9) > 15)
int a = 9
would be evaluated before reaching the while condition, thus being out of the scope we just defined. We wouldn't enter the while block, but the value of a is well defined! Makes sens why it doesn't happen, doesn't it ?
If we go the other way and says that it is just a shortcut for this:
int a;
while((a = 9) > 15)
Then the language wouldn't be consistent and would bring many confusing code! See the for
loop, the variable defined in it is scoped in it not outside for example.
It still doesn't make any sens why it's not possible to do in javascript though. However I don't care enough to find out.
I hope I made it clear, at least it makes some sens to me and I learned something. On a side note, I don't think my question really warranted so much down votes, even tho the answer seems obvious to me now. Not every question on stackoverflow has to be a practical one..