Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top