Liam B
Liam B

Reputation: 55

declaring a variable within conditional expressions (ternary operator)

Is it possible to declare the variable within a conditional expression?

for example: The code below return a syntax error (because I've declared the variable x within the conditional expression?).

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 possible for variables to be declared here?

Upvotes: 3

Views: 3484

Answers (3)

Dvir
Dvir

Reputation: 3339

No. But you can initialize it with undefined and set it with condition.

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074218

Is it possible to declare the variable within a conditional expression?

No. var is a statement, and the operands to a conditional expression are expressions. The language grammar doesn't allow it. Thankfully.

Upvotes: 9

cdhowie
cdhowie

Reputation: 168998

You can do this with an immediately-invoked function:

(d.length>15)?(
    alert("your input was too long")):
    (function(){
        var x = parseInt(d).toString(2);
        a.value=x;
    }())
);

But note that the x variable will not exist outside of the inner function. (I can't tell whether you want it to exist after the expression is evaluated or not.)

Upvotes: 1

Related Questions