if ([expression]) { [statement] } var a = 10; if (a > 3) { console.log(‘it is true’) } // Bad style, always use braces if (a > 5) console.log(‘it is true’); if (a && a === ‘someString’) { console.log(1); } else if (a || b) { console.log(2); } else if ((c + 5) < 10 ) { console.log(3); } else { console.log(4); }
var i = 1, j = 1, k = 2; // developer doesn't use braces if (i == j) if (j == k) alert("i is the same as k"); else alert("i isn't the same as j"); // as a result, code works wrong if (i == j) { if (j == k) { alert("i is the same as k"); } else { alert("i isn't the same as j"); // OOPS! } }
var i = 1, j = 5, result; // bad approach, try to avoid it if (i != j) { result = true; } else { result = false; } // the same, but easier result = i != j;
var salary = 90000, reaction = ''; // To define reaction we can use simple if statement if (salary > 50000) { reaction = 'Not bad!'; } else { reaction = 'WTF?!!'; } // But I'd rather use this one reaction = a > 50000 ? 'Not bad!' : 'WTF?!!';
switch (city) { case: "Lviv" console.log("Hi Lviv"); break; case: "Kiev" console.log("Hi Kiev"); break; case: "Ternopil" console.log("Hi Ternopil"); break; default: console.log("Hi Unknown city"); break; }
var i = 0; while (i < 10) { console.log(i); i++; } console.log(i);
var i = 0; do { console.log(i); i++; } while (i < 10) do { var name = prompt("Who are you?"); } while (!name); console.log(name);
for ([initialization]; [test]; [increment]){ [statement] } // the most common use for (var i = 0; i < 10; i++) { console.log(i); } console.log(i); //10
// we can move initialization var i = 0; for (; i < 10; i++) { console.log(i); } // we can move increment for (; --i;) { console.log(i); } // finally we can remove everything for (;;) { if (i == 0) { console.log(i); break; } }
for (var i = 0; i < 10; i++) { console.log(i); if(i % 2 == 0) { continue; } console.log(i); if(i == 9) { break; } } console.log(i); //10