I get unexpected result for this simple JavaScript assignment statement:
var t = 1 == 1 ? 1 : 0;
undefined
I would have expected to get 1 assigned to t instead. Same result if you do
var t = (1 == 1 ? 1 : 0);
undefined
Can somebody explain why this does not work as expected?
It works perfectly:
You could say that the return value of the assignment operation isundefined, not the value oft.Edit: But actually if I read the specification correctly, it seems that it should return the value of the expression.
As @T.J. Crowder mentioned, it seems the
varis responsible for theundefinedvalue. But that does not mean that you should not usevar. The code you wrote is 100% correct.This goes more into the inner workings of the language and I think that is not what you are interested in. Bur for more information about that, have a look at the comments.