Skip to content

Files

Latest commit

 

History

History
142 lines (108 loc) · 1.48 KB

002_0_statements-and-loops.md

File metadata and controls

142 lines (108 loc) · 1.48 KB

Loops and conditional statements

Conditional statements

if... else

if (condition) {
  // ...
} else if (anotherCondition) {
  // ...
} else {
  // ...
}

switch... case

switch (somethingToCompare) {
  case 'againstSomething': 
    // ...
    break;

  case 'againstAnotherSomething':
    // ...
    break;

  default:
    // ...
}

Loops

Remember to have always an exit condition to avoid entering into an infinite loop

while

while (condition) {
  // ...
}

Example:

let i = 1;

while (i < 4) {
  console.log(i);
  i++;
}

// 1
// 2
// 3

do... while

First executes and then evaluates condition. So, the statement is executed at least once.

do {
  // ...
} while (condition);

for

for (initialExpression; condition; incrementOrDecrement) {
  // ...
}

Example:

for (let i = 1; i < 4; i++) {
  console.log(i)
}

// 1
// 2
// 3

for... in

In arrays it will return each index as string In objects it will return the object keys

const arr = ['Hi','Hello','Hola']

for (let el in arr) {
  console.log(el);
}

// '0'
// '1'
// '2'

const obj = {
  prop1: 1,
  prop2: 2,
  prop3: 3
}

for (let prop in obj) {
  console.log(prop);
}

// 'prop1'
// 'prop2'
// 'prop3'

for... of

const arr = ['Hi','Hello','Hola']

for (let el of arr) {
  console.log(el);
}

// 'Hi'
// 'Hello'
// 'Hola'