Variable declaration in conditional expressions (ternary operator)
Can I declare a variable in a conditional expression?
eg: The code below returns a syntax error (because I declared the variable x in the conditional statement?).
var a = document.getElementById("userData");
var d = a.value;
function() {
(d.length>15)?(
alert("your input was too long")):(
var x = parseInt(d).toString(2),
a.value=x
);
}
obviously this can be fixed by simply adding var x;
outside the statement, but is it okay to declare variables here?
source to share
Can I declare a variable in a conditional expression?
Not. var
is an operator, and the operands of a conditional expression are expressions. The language grammar does not allow this. Fortunately.
source to share
You can do this with an immediately called function:
(d.length>15)?(
alert("your input was too long")):
(function(){
var x = parseInt(d).toString(2);
a.value=x;
}())
);
But note that the variable x
will not exist outside of the inner function. (I can't tell if you want it to exist after evaluating the expression or not.)
source to share