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?

0


source to share


3 answers


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.

+7


source


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.)

+1


source


Not. But you can initialize it with undefined

and set it conditionally.

function Test()
{
    d = 25.6654;
    var x = (d.toString().length > 15) ? parseInt(d).toString() : undefined;

    alert(typeof x === "undefined");
}

      

Then you can work with if(typeof x == "undefined") //do something

0


source







All Articles