Javascript loops and values -
my book says , i'm not entirely sure means. says make sure loop executes properly, need include code change value of conditional expression? mean? correct? may reading wrong when have basic javascript loop
if(contactscount > 0) { (i = 0; < contactscount; = + 1){ var item = object[i], name = item.name, email = item.email; target.innerhtml += '<p><a href=mailto:' + email + '">' + name + '</a>!</p>; } } })();
surely aren't changing values make work? i'm new i'm kind of clueless.
...you need include code change value of conditional expression? mean?
that bad idea:
var = 0; while (i < 10) { dosomething(i); }
why? because loop never end. i
's value never changed. endless loops classic form of bug.
so book saying must provide way loop condition (i < 10
) change (e.g., modifying i
's value).
a bit of tangent, but:
sometimes see loops condition seemingly can't change, e.g.:
while (true) { // ... }
if find reaching that, stop , try find better way. there rare use cases above, this:
while (true) { dothis(); dothat(); if (somecondition) { break; } doanotherthing(); }
...so in case, controlling condition in middle, , 1 in looping statement isn't condition. poor practice, in very rare situations can right thing do.
it says can have other statements on same line "if statement", right?
yes, is. javascript doesn't care lines at all (except when it's doing form of error-correction called automatic semicolon insertion; lines matter because linebreaks stand in semicolons part of error-correction algorithm). of these valid , same thing:
// 1 if (a < b) { alert("a less b"); foo(); } // 2 if (a < b) { alert("a less b"); foo(); } // 3 if (a < b) { alert("a less b"); foo(); } // 4 if (a < b) { alert("a less b"); foo; }
because javascript doesn't care lines @ all, they're matter of style.
by far, common style above #1.
separately, if have single statement in control-flow statement's body, block (the {...}
) optional. these same thing:
// 1 if (a < b) { alert("a less b"); } // 2 if (a < b) alert("a less b"); // 3 if (a < b) alert("a less b");
so using {...}
single statement in body also, technically, matter of style. in practice, however, using blocks leads fewer bugs in code. if leave off blocks, will bite when add second statement , forget add block:
if (a < b) alert("a less b"); foo();
in above, foo()
always called, because it's not in body of if
. code this:
if (a < b) { alert("a less b"); } foo();
great
ReplyDelete