0

Is there a condensed way of defining a variable within the condition of an if statement in JavaScript? For example:

var arr = [1,2,3];
console.log(len); // output is null, since it was never declared
if ((var len = arr.length) > 0) { // len  == 3
    // logic using variable 'len ' here
}

Or is the only way around this to declare and assign the value of len before the conditional statement?

2
  • Why not using only arr.lenght in the conditional statement and then declare the variable len inside of it?
    – steps
    Feb 13, 2015 at 2:11
  • That would make it a line longer, I'm just trying to see if there is a condensed way of doing it.
    – rageandqq
    Feb 13, 2015 at 2:14

2 Answers 2

2

If your concern is the number of lines you write, you can declare len in the same line where you declare arr such as:

var len, arr = [1,2,3];
console.log(len); 
if ((len = arr.length) > 0) { // len  == 3
    // logic using variable 'len ' here

    console.log(len); 
}

I personally avoid setting values in conditionals. Conditionals are no place to set variables. It looks like an error, it leads to errors and people that read your code will be likely to miss that a variable is being set in the conditional statement.

Good luck!

1
  • @rageandqq your code doesn't work, the variable must be declared outside the condition. It can be assigned in the condition though. I would advise against this because it often looks like an accident and that it should be == or === Feb 13, 2015 at 2:22
0

Based on the comment from @VictorJohnson in the other answer, I would declare my variables like below

var arr = [1,2,3], len=arr.length;
console.log(len);             // len == 3
if (len > 0) {
    // logic using variable 'len ' here

    console.log(len); 
}

This removes the possible confusion of the if block and remains quite condensed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.