Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
var fruitList = [];
var fruitExpired = GetFruitStatus();
var fruitName = "Mango";
var companyName = "Limited";

if(fruitExpired)
{
   var expiredCrateId = GetExpiredCrate().ID;
   list.push({
    expiredCrate : expiredCrateId,
    fruitName : name,
    fruitCompany : companyName
   });
}
else
{
   var CrateId = GetCrate().ID;
   list.push({
    crateId : expiredCrateId,
    fruitName : name,
    fruitCompany : companyName
   });
}

Can I bring list.push outside if else ? this will help remove duplicate code, only difference is that if expired I am adding property expiredCrate : expiredCrateId, otherwise crateId : expiredCrateId,

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You can create a fruit with the common properties before the if:

var fruitList = [];
var fruitExpired = GetFruitStatus();
var fruitName = "Mango";
var companyName = "Limited";

var fruit = {
    fruitName: name,
    fruitCompany: companyName
}

if (fruitExpired) {
    fruit.expiredCrate = GetExpiredCrate().ID;
} else {
    fruit.crateId = GetCrate().ID;
}

list.push(fruit);

Also, beware where you put { } in your code, it's not C# and a { after if or else should be on the same line.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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