Reputation: 8492
I'm wondering if there's a way to merge shorthand if/else with shorthand +=
Something like this:
var value;
$.each(data.events, function(index, element) {
var otherValue = element.value;
value = value ? value + otherValue : '';
}
Something to prevent
value += otherValue
From adding 'undefined' to the beginning when value is undefined.
The long version would be:
var value;
$.each(data.events, function(index, element) {
var otherValue = element.value;
if(value){
value = value + otherValue;
}
}
I hope the question is not (too) confusing :)
Upvotes: 0
Views: 1558
Reputation: 11440
Edit:
Geeze what I posted is almost the exact opposite of what you had in your bottom example. I would have deleted my question here but its accepted =/
You can use the AND &&
operator:
console.log('foo' && 'hello'); // prints hello
console.log(null && 'hello'); // prints null
console.log(undefined && null); // prints undefined
console.log('foo' && null && 'bar'); // prints null
var value;
$.each(data.events, function(index, element) {
// if value is undefined, null, or empty then it stays the same.
// otherwise add append the element value
value = (value && value + element.value);
}
although this isnt much more readable than your original
var value;
$.each(data.events, function(index, element) {
// if value is undefined, null, or empty then it stays the same.
// otherwise add append the element value
if(value) value += otherValue;
}
I left my original answer below, I had read your question and saw your first code snippet and answered to that. However your 2nd code snippet does something different, im not really sure what answer is right now...
You could ||
operator which will return the first undefined value it saw as the expression is true (eg:!!val === true
) or the last value in the operator sequence (assuming your using all OR statements ||
)
console.log(undefined || 'hello'); // prints hello
console.log('' || 'hello'); // prints hello
console.log(undefined || null); // prints null
console.log(undefined || '' || null); // prints null
So in your case taking your working but longer JavaScript code we can simplify it to the following
var value;
$.each(data.events, function(index, element) {
value = (value && value+element.value);
}
Upvotes: 1
Reputation: 5632
Just like this:
value = value && value + otherValue || value
another possible way would be:
value && (value += otherValue)
it's just like if value
is truthy evaluate the next term (value += otherValue)
Though I would not go for these paths, I think one of the things we need to consider in coding is not just about how short our code is, but also readability.
I would still prefer
if(value)
value += otherValue;
because it is easier to read and see that you had a condition there
Upvotes: 1