Reputation: 2281
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?
Upvotes: 0
Views: 47
Reputation: 6170
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
Upvotes: 0
Reputation: 915
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!
Upvotes: 2