JavaScript · Syntax · Beginner

For loop and arrays

15 tasks

JavaScript for loop practice on arrays: looping through elements, filtering values, counting, finding minimums and maximums, working with strings, dates, and nested data.

The for...of loop and arrays

#
JavaScript has no tuples — arrays cover both use cases. The idiomatic way to iterate over an array is the for...of loop: ```javascript const numbers = [3, 7, 1, 9, 4]; for (const n of numbers) { console.log(n); } ``` Each iteration, n holds the next element. When the array runs out, the loop ends. The same syntax works on strings — they iterate character by character. for...of was introduced in ES6 and is the preferred modern syntax. Older code uses index-based for loops — you will see both in the wild, but for...of reads more clearly for most tasks. When you need both the index and the value, use entries(): ```javascript const days = ["Monday", "Tuesday", "Wednesday"]; for (const [i, day] of days.entries()) { console.log(`Day ${i + 1}: ${day}`); } ``` entries() produces [index, value] pairs. The destructuring [i, day] unpacks each pair in the loop header. This is the JavaScript equivalent of Python's enumerate().

Building arrays while iterating

#
Many for-loop tasks follow the same shape: start with an empty array, loop over the source, decide whether to include each element, and push the keepers. ```javascript const numbers = [2, 5, 0, 8, 11, 14, 17, 0]; const result = []; for (const n of numbers) { if (n % 2 === 0 && n !== 0) { result.push(n); } } console.log(result); ``` push() adds an element to the end of an array. It is the equivalent of Python's append(). Accumulating a total: ```javascript const numbers = [5, 10, 15, 20]; let total = 0; for (const n of numbers) { total += n; } console.log(total); ``` Tracking the current maximum — start with the first element, update when you find something bigger: ```javascript const numbers = [8, 3, 15, 6, 2]; let maxNum = numbers[0]; for (const n of numbers) { if (n > maxNum) { maxNum = n; } } console.log(maxNum); ``` Starting with numbers[0] instead of 0 matters. If all numbers are negative, starting at 0 would give the wrong answer.

Key patterns from the exercises

#
Joining array elements into a string — JavaScript arrays have a built-in join() method: ```javascript const numbers = [3, 7, 1, 9, 4]; const result = numbers.join("-"); console.log(result); // 3-7-1-9-4 ``` join() converts each element to a string automatically. No need for explicit conversion unless you want to format individual values first. Building an array of pairs — combine each element with computed data: ```javascript const words = ["JavaScript", "is", "fast"]; const result = []; for (const word of words) { result.push([word, word.length]); } console.log(result); // [['JavaScript', 10], ['is', 2], ['fast', 4]] ``` Filtering by a property of a string: ```javascript const words = ["javascript", "java", "go", "python", "c"]; let count = 0; for (const word of words) { if (word.length > 5) { count++; } } console.log(count); ``` Parsing structured data — split a string on a separator, then compare parts. The date filter exercise uses this: split on "-", then compare year and month values as numbers.
01

Numbers separated by hyphens.

#

Given an array of numbers. Print each number from the array on the same line in the terminal separated by hyphens. 3-7-1-9-4

let numbers = [3, 7, 1, 9, 4];
Solution
let numbers = [3, 7, 1, 9, 4];
let result = "";
for (let n of numbers) {
    result += String(n) + "-";
}
result = result.slice(0, -1);
console.log(result);

// or the shortest version using join
let numbers = [3, 7, 1, 9, 4];
let result = numbers.join("-");
console.log(result);
02

Even numbers without zeros.

#

Given an array of numbers. Add only even numbers to a new array, skipping zeros.

let numbers = [2, 5, 0, 8, 11, 14, 17, 0];
let newItems = [];
Solution
let numbers = [2, 5, 0, 8, 11, 14, 17, 0];
let newItems = [];
for (let n of numbers) {
    if ((n !== 0) && (n % 2 === 0)) {
        newItems.push(n);
    }
}
console.log(newItems);

// or like this: first check for zero, then for evenness
let numbers = [2, 5, 0, 8, 11, 14, 17, 0];
let result = [];

for (let n of numbers) {
    if (n === 0) {
        continue;
    }
    if (n % 2 === 0) {
        result.push(n);
    }
}

console.log(result);
03

Sum of array elements.

#

Given an array of numbers. Find the sum of all array elements.

let numbers = [5, 10, 15, 20];
let total = 0;
Solution
let numbers = [5, 10, 15, 20];
let total = 0;
for (let n of numbers) {
    total += n;
}
console.log("Sum:", total);

// or like this using reduce, when this method is already familiar
let numbers = [5, 10, 15, 20];
let total = numbers.reduce((sum, n) => sum + n, 0);
console.log("Sum:", total);
04

Non-empty strings.

#

Given an array of strings. Add non-empty strings to a new array.

let words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""];
let newWords = [];
Solution
let words = ["0000-0000-0000-0000", "", "1111-1111-1111-1111", "2222-2222-2222-2222", ""];
let newWords = [];
for (let w of words) {
    if (w !== "") {
        newWords.push(w);
    }
}
console.log(newWords);
05

Squares of numbers greater than 10.

#

Given an array of numbers. Create a new array containing squared values only for numbers greater than 10.

let numbers = [3, 12, 5, 18, 7, 25];
let result = [];
Solution
let numbers = [3, 12, 5, 18, 7, 25];
let result = [];
for (let n of numbers) {
    if (n > 10) {
        result.push(n ** 2);
    }
}
console.log(result);

// or like this: first save the square into a variable
let numbers = [3, 12, 5, 18, 7, 25];
let result = [];

for (let n of numbers) {
    if (n > 10) {
        let square = n ** 2;
        result.push(square);
    }
}

console.log(result);
06

Days of the week with numbers.

#

Given an array with names of weekdays. Print each day in the format: "Day X: <name>".

let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
Solution
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
let dayNum = 1;
for (let day of days) {
    console.log(`Day ${dayNum}: ${day}`);
    dayNum += 1;
}

// or like this using a regular index
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

for (let i = 0; i < days.length; i += 1) {
    console.log(`Day ${i + 1}: ${days[i]}`);
}
07

Maximum using a loop.

#

Given an array of numbers. Find the maximum number in the array using a for loop.

let numbers = [8, 3, 15, 6, 2];
let maxNum = numbers[0];
Solution
let numbers = [8, 3, 15, 6, 2];
let maxNum = numbers[0];

for (let n of numbers) {
    if (n > maxNum) {
        maxNum = n;
    }
}

console.log("Maximum:", maxNum);

// or like this
let numbers = [8, 3, 15, 6, 2];
let maxNum = Math.max(...numbers);
console.log("Maximum:", maxNum);
08

Strings longer than 5 characters.

#

Given an array of strings. Count how many strings are longer than 5 characters.

let words = ["javascript", "java", "go", "javascript", "c"];
let count = 0;
Solution
let words = ["javascript", "java", "go", "javascript", "c"];
let count = 0;
for (let w of words) {
    if (w.length > 5) {
        count += 1;
    }
}
console.log("Number of strings:", count);
09

Positive numbers from an array.

#

Given an array of numbers. Print only the numbers greater than 0.

let numbers = [-3, 5, -1, 7, 0, -2];
Solution
let numbers = [-3, 5, -1, 7, 0, -2];
for (let n of numbers) {
    if (n > 0) {
        console.log(n);
    }
}
10

String separated by commas.

#

Given an array of strings. Create a string consisting of all array elements separated by commas and spaces.

let words = ["JavaScript", "is", "cool"];
let result = "";
Solution
let words = ["JavaScript", "is", "cool"];
let result = "";
for (let w of words) {
    result += w + ", ";
}
result = result.slice(0, -2);
console.log(result);

// or shorter using join
let words = ["JavaScript", "is", "cool"];
let result = words.join(", ");
console.log(result);
11

Words and their lengths.

#

Would you be so kind 🧐 as to create a new array from this array of strings, where the elements will themselves be arrays. Each inner array should contain two elements: the string and its length. For example: words = ["JavaScript", "is", "cool"] new = [["JavaScript", 10], ["is", 2], ["cool", 4]]

let words = ["JavaScript", "is", "cool"];
let newItems = [];
Solution
let words = ["JavaScript", "is", "cool"];
let newItems = [];
for (let word of words) {
    let t = [word, word.length];
    newItems.push(t);
}
console.log(newItems);

// or like this without an intermediate variable
let words = ["JavaScript", "is", "cool"];
let result = [];

for (let word of words) {
    result.push([word, word.length]);
}

console.log(result);
12

String characters in lowercase.

#

Hmm... We urgently need to make an array from this string "This", consisting of the characters of this string in lowercase!!! (small letters)

let word = "This";
Solution
let word = "This";
let arr = Array.from(word.toLowerCase());
console.log(arr);

// or through a loop to clearly see each character being added
let word = "This";
let arr = [];

for (let char of word) {
    arr.push(char.toLowerCase());
}

console.log(arr);
13

Card number with dashes.

#

Again, urgently! Some genius saved a bank card number as an array of groups of 4 digits: card = ["1111", "2222", "3333", "4444"] Convert this into a string in the format: normCard = "1111-2222-3333-4444"

let card = ["1111", "2222", "3333", "4444"];
Solution
let card = ["1111", "2222", "3333", "4444"];

let normCard = card.join("-");

console.log(normCard);

// or like this:
let card = ["1111", "2222", "3333", "4444"];

let normCard = "";

for (let part of card) {
    normCard += part + "-";
}

normCard = normCard.slice(0, -1);

console.log(normCard);
14

Minimum, maximum, and average.

#

Continuing the urgent quest! Quickly find: - the minimum value in the array; - the maximum value in the array; - the sum of all values in the array; - the average of the values in the array. And then, if you want, do it not so quickly.

let arr = [10, 100, 500, 11, 18, 99, -3, 101];
Solution
// quick way

let numbers = [5, 2, 9, 1, 7];

let minNum = Math.min(...numbers);
let maxNum = Math.max(...numbers);

let total = numbers.reduce((sum, n) => sum + n, 0);

let average = total / numbers.length;

console.log("Minimum:", minNum);
console.log("Maximum:", maxNum);
console.log("Sum:", total);
console.log("Average:", average);

// not so quick way

let numbers = [5, 2, 9, 1, 7];

let minNum = numbers[0];
let maxNum = numbers[0];
let total = 0;

for (let n of numbers) {
    if (n < minNum) {
        minNum = n;
    }

    if (n > maxNum) {
        maxNum = n;
    }

    total += n;
}

let average = total / numbers.length;

console.log("Minimum:", minNum);
console.log("Maximum:", maxNum);
console.log("Sum:", total);
console.log("Average:", average);
15

Filter dates after 2027.09.01.

#

Finally, 5 minutes before the end of the workday: There is an array with dates in the strict format yyyy.mm.dd: dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"] We need a new array containing only dates after 2027.09.01. Hint: try comparing strings using < and >, sometimes it's useful 😉.

let dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"];
let newItems = [];
Solution
let dates = ["2027.09.25", "2027.10.14", "2027.03.01", "2027.12.29", "2027.09.11", "2027.05.06"];
let newItems = [];
for (let date of dates) {
    if (date >= "2027.09.01") {
        newItems.push(date);
    }
}
console.log(newItems);