h0dges h0dges - 4 days ago 6
Javascript Question

Correct way to introduce if statement to specific for loop?

EDIT: Just to clarify, as zer00ne spotted this was originally minified code that I "beautified" in order to modify it. Apologies for not making that clear sooner.

Original for loop, that works:

m = 0;
for (k = b.header.length; m < k; m++) d.appendChild(p(e, "col", {
attr: {
min: m + 1,
max: m + 1,
width: N(b, m),
customWidth: 1
}
}));


What I want to do, but doesn't work:

m = 0;
for (k = b.header.length; m < k; m++) d.appendChild(p(e, "col", {
if (m==6) {
attr: {
min: m + 1,
max: m + 1,
width: 100,
style: 2,
customWidth: 1
}
} else {
attr: {
min: m + 1,
max: m + 1,
width: N(b, m),
customWidth: 1
}
}
}));


I understand that the if statement is in the wrong place w.r.t. the function d.appendChild, but I'm not sure how to separate the for loop from the function in order to place the if statement in the correct position. Finally what is this style of for loop/function hybridisation called?

Help?

Answer

It's not about for loop, it's about possibility to use if inside object literal. In short, there's none.

What you might do instead is extend a specific param based on condition, like this:

var m = 0;
var attr;
for (var k = b.header.length; m < k; m++) {
  attr = {
    min: m + 1,
    max: m + 1,
    customWidth: 1
  };
  if (m === 6) {
    attr.style = 2;
    attr.width = 100;
  }
  else {
    attr.width = N(b, m);
  }
  d.appendChild(p(e, 'col', { attr: attr }));
}

This approach is DRY: the attributes common for both cases are specified once (so it's easier to modify them).

Have you worked with just a single varied param, there would have been another way to do this - with ternary:

attr = {
  min: m + 1,
  max: m + 1,
  width: m === 6 ? 100 : N(b, m),
  customWidth: 1
};

Still, there's another thing to consider: what's 6? It's not clear to any reader - including you several months (or even weeks, depending on the codebase's size) later.

Comments