admin管理员组

文章数量:1356240

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?

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?

Share Improve this question asked Sep 28, 2013 at 21:21 Liam BLiam B 551 silver badge5 bronze badges 5
  • 1 ... why would you want to do that? – user395760 Commented Sep 28, 2013 at 21:24
  • I would use if..else in this case and keep it readable. – karthikr Commented Sep 28, 2013 at 21:25
  • No. Then would something like var a = (var b!=undefined) ? (var c=1) : (var d=2); be legal – davidkonrad Commented Sep 28, 2013 at 21:27
  • @delnan honestly, just curiosity. i don't think it has any benefits other than shortening my code by a character or two. – Liam B Commented Sep 28, 2013 at 21:31
  • @LiamB You should aim for readable, not short. Needlessly short code is often too clever to be easily understood by the next person who has to maintain your code. (Or even by yourself when you e back to the code a month later.) – cdhowie Commented Sep 28, 2013 at 21:31
Add a ment  | 

3 Answers 3

Reset to default 9

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.

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

本文标签: javascriptdeclaring a variable within conditional expressions (ternary operator)Stack Overflow