06_JavaScript: for / while / for.. of

06_JavaScript: for / while / for.. of

Loop statement(iteration) / Array / Object

·

2 min read

Ex01. for

for (let i = 0; i < 10; i++){
    console.log(i);
}

for (let i = 10; i > 0; i--) {
  console.log(i);
}

Ex02. for & array

const names = ['dog', 'cat', 'turtle']; //array
for(let i=0; i<names.length; i++) {
    console.log(names[i]); //dog cat turtle
}

Ex03. while

let i =0;
while (i<10) {
    console.log(i);
    i++;
}

Ex04. Array Loop - for...of

  • We don't really use this. The built-in function of Array is more useful.
let numbers = [10, 20, 30, 40, 50];
for (let number of numbers) {
    console.log(number);
}

Ex05. Object Loop - entries, keys, values or for .. in

  • Object.entries()

  • Object.keys()

  • Object.values()

// object
const doggy = {
    name : 'siru',
    sound: 'bowwow',
    age: 2
};
// change object into Array 
console.log(Object.entries(doggy)); //[['name', 'siru'],['sound', 'bowwow'],['age', 2]]
console.log(Object.keys(doggy)); // ['name', 'sound', 'age']
console.log(Object.values(doggy)); // ['siru', 'bowwow', 2]
// object
const doggy = {
    name : 'siru',
    sound: 'bowwow',
    age: 2
};
for(let key in doggy) {
    console.log(`${key}: ${doggy[key]}`);
}

Ex06. break, continue

for (let i=0; i<10; i++) {
    if ( i == 2 ) continue; // goto 'for (let i=0; i<10; i++)'
    console.log(i);
    if ( i == 5 ) break; // finish
}

Ex07. Practice: make sum function

// The array 'numbers'
function sumOf(numbers) {
    let sum = 0;
    for (let i = 0; i < numbers.length; i++) {
        sum += numbers[i];
    }
    return sum;
}
const result = sumOf([1, 2, 3, 4, 5]);
console.log(result); //15

Ex08. Quiz : make a new array with numbers that is bigger than 3

function biggerThanThree(numbers) {
    k = []
    for (let number of numbers) {
        if(number > 3) {
            k.push(number)
        }
    }
    return k
}
const numbers = [1, 2, 3, 4, 5, 6, 7];
console.log(biggerThanThree(numbers)); // [4, 5, 6, 7]
function biggerThanThree(numbers) {
    return numbers.filter((number) => number > 3);
}
const numbers = [1, 2, 3, 4, 5, 6, 7];
console.log(biggerThanThree(numbers)); // [4, 5, 6, 7]

cf. https://learnjs.vlpt.us/basics/08-loop.html