Developer Snippet Diary

Loops & if else conditions in javascript

1.if

if (condition) {
  //  block of code to be executed if the condition is true
}

2.if else

if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}

3.if else if

if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

4.switch

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

5.For Loop

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

6.FOR IN (properties of object read)

var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
  text += person[x];
} 
//////////////// OR

for (var key in person) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

7.FOR OF (iterable for objects ,arrays, nodes,strings etc)

var cars = ['BMW', 'Volvo', 'Mini'];
var x;
for (x of cars) {
  document.write(x + " "); //BMW Volvo Mini
}

8.while

while (i < 10) {
  text += "The number is " + i;
  i++;
}

9.do while 

do {
  text += "The number is " + i;
  i++;
}
while (i < 10);

10.break; //break statement used to jump out of a loop. 

for (i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

11.continue;// jump out one iteration

for (i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}

12. Loop objects with keys

 let future_all_coins = {'usd':1,'btc','38000','ltc':108};
  var future_all_coins_keys = Object.keys( future_all_coins);

  for(let coin of future_all_coins_keys){
    console.log(coin+" "+future_all_coins[coin]);
  }
Posted by: R GONDAL
Email: rizikmw@gmail.com