JavaScript Multiple Values

Arrays, Objects, Array Methods - Complete Learning Notes

Javascript Multiple Values

A program may not always requires to store single values, if the data grows we need a mechanism to address the growing need of storing multiple values to a variable in the program.

To address this problem javascript programming language introduced Arrays and Objects.

Arrays – ordered lists of values (like a numbered shelf).

Objects – collections of named properties (like a dictionary of key–value pairs).

Arrays

An array is an ordered collection where each value has a numeric index starting at 0. Conceptually:

Syntax:
let arrayVarName = []; // Array created as empty
let arrayVarName = [val1,val2,…,valn]; // Array created with list of values
Example:
let languages = ["JS","Java","Python"];

Index: 0 1 2

Value: "JS" "Python" "Java"

You access values of an array by index, not by name.

Example:

Console.log(languages[0]); //Output: JS

Key points:

Square brackets [] define the array literal.

Elements are separated by commas.

Arrays can contain mixed types (though in real projects you usually keep them consistent).

Mixed-type array

Example:
let mixed = ["Alice", 25, true];
console.log(mixed[0]); // line 3
console.log(mixed[1]); // line 4
console.log(mixed[2]); // line 5

Array indices and length

Each element is stored at an index: first element at index 0, second at index 1, and so on. The array has a length property: the number of elements.

let colors = ["red", "green", "blue"];

Index: 0 1 2

Value: "red" "green" "blue"

colors.length --> 3
Example 3 – Using length and indices

javascript

let colors = ["red", "green", "blue"];
console.log(colors.length);  // line 3
console.log(colors[colors.length - 1]); // line 4

Explanation:

let colors = ["red", "green", "blue"];
Declares an array with three elements.
console.log(colors.length);
Prints the length, which is 3.
console.log(colors[colors.length - 1]);
Computes index 3 - 1 = 2 and prints the last element, "blue".

Modifying arrays: reading, writing, and methods

You can:

Read elements: array[index]

Write/replace elements: array[index] = newValue

JavaScript arrays have many built-in methods

1. Add & Remove Elements

let arr = [2, 3];
arr.push(4);      // [2, 3, 4]
arr.unshift(1);   // [1, 2, 3, 4]
arr.pop();        // [1, 2, 3]
arr.shift();      // [2, 3]

An Arrow Function is a shorter way to write a function. It was introduced in ES6 (ECMAScript 2015).

Syntax
(parameters) => {

// function body

}

2. Iterate Through Arrays

forEach()

Executes a function for each element.

const numbers = [1, 2, 3];
numbers.forEach(num => {

console.log(num);

});

numbers.forEach((num,index) => {

console.log(index," ",num);

});

3. Transform Arrays

map()

Returns a new array.

const nums = [1, 2, 3];
const doubled = nums.map(num => num * 2);
console.log(doubled);
// [2, 4, 6]

4. Filter Arrays

filter()

Returns elements that satisfy a condition.

const nums = [1, 2, 3, 4, 5];
const even = nums.filter(num => num % 2 === 0);
console.log(even);
// [2, 4]

5. Find Elements

find()

Returns the first matching element.

const nums = [10, 20, 30];
const result = nums.find(num => num > 15);
console.log(result);
// 20
findIndex()
const index = nums.findIndex(num => num > 15);
console.log(index);
// 1

6. Test Conditions

some()

Returns true if at least one element matches.

const nums = [1, 2, 3];
console.log(nums.some(num => num > 2));
// true
every()

Returns true if all elements match.

console.log(nums.every(num => num > 0));
// true

7. Reduce Arrays

reduce()

Reduces the array to a single value.

const nums = [1, 2, 3, 4];
const sum = nums.reduce((total, num) => total + num, 0);
console.log(sum);
// 10

8. Search Arrays

includes()

const fruits = ["apple", "banana"];
console.log(fruits.includes("banana"));
// true

indexOf()

console.log(fruits.indexOf("banana"));
// 1

9. Slice & Splice

slice()

Returns a portion without modifying the original.

const arr = [1, 2, 3, 4];
console.log(arr.slice(1, 3));
// [2, 3]
console.log(arr);
// [1, 2, 3, 4]
splice()

Modifies the original array.

const arr = [1, 2, 3, 4];
arr.splice(1, 2);
console.log(arr);
// [1, 4]

10. Join & Split

join()

const words = ["Hello", "World"];
console.log(words.join(" "));
// "Hello World"
//split()
let stmt = "Today is saturday";
console.log(stmt.split(" "));

[ 'Today', 'is', 'saturday' ]

11. Sort & Reverse

sort()
const nums = [3, 1, 5, 2];

nums.sort();

console.log(nums);
// [1, 2, 3, 5]
reverse()
const arr = [1, 2, 3];
arr.reverse();
console.log(arr);
// [3, 2, 1]

12. Combine Arrays

concat()
const a = [1, 2];
const b = [3, 4];
const result = a.concat(b);
console.log(result);
// [1, 2, 3, 4]

13. Flatten Arrays

flat()
const arr = [1, [2, 3], [4, [5]]];
console.log(arr.flat());
// [1, 2, 3, 4, [5]]
flatMap()
const arr = ["hello world", "javascript"];
const words = arr.flatMap(str => str.split(" "));
console.log(words);
// ["hello", "world", "javascript"]

14. Create Arrays

Array.from("hello");
// ["h", "e", "l", "l", "o"]
Array.of(1, 2, 3);
// [1, 2, 3]
new Array(3);
// [empty × 3]

Array(3).fill(0);

// [0, 0, 0]

15. Fill Arrays

fill()
const arr = [1, 2, 3];
arr.fill(0);
console.log(arr);
// [0, 0, 0]

16. Check Array Type

Array.isArray([1, 2]);
// true
Array.isArray("hello");
// false

Quick Interview Cheat Sheet

Loops

Loops are control-flow structures that repeatedly execute a block of code as long as a specified condition is satisfied. They are essential for tasks such as:

Repeating operations a fixed number of times

Iterating through arrays and objects

Generating sequences (for example, Fibonacci numbers)

The following loop constructs are:

while loop
do...while loop
for loop

Nested loops

Loops with arrays

for...of loop

Loops with objects (for...in and object-to-array approaches)

break and continue (including in nested loops and labeled blocks)

2. while Loop

2.1 Concept and Syntax

A while loop executes its body as long as its condition evaluates to true.

Basic syntax:

while (condition) {

// code that executes while condition is true

}

The condition is evaluated before each iteration.

If the condition is initially false, the loop body is skipped entirely.

2.2 Simple counting example

This example prints numbers from 0 up to (but not including) 10.

let i = 0;
while (i < 10) {

console.log(i);

i = i + 1;

}

Line-by-line explanation:

let i = 0;
Declares a variable i and initializes it to 0; this is our loop counter.
while (i < 10) {
Starts the loop; the body will execute while i is less than 10.
console.log(i);
Outputs the current value of i to the console.

i = i + 1; Increments i by 1 so that the loop progresses toward the stopping condition.

When i reaches 10, the condition i < 10 becomes false and the loop stops.

2.3 Searching in an array with while

Example: find a specific value in an array and stop when found, or when the array is exhausted.
let someArray = ["Mike", "Antal", "Marc", "Emir", "Louiza", "Jacky"];
let notFound = true;
while (notFound && someArray.length > 0) {
  if (someArray[0] === "Louiza") {

console.log("Found her!");

notFound = false;

} else {

someArray.shift();

}

}

console.log(notFound);

Explanation:

someArray holds several names.

notFound is a Boolean that indicates whether we have already found "Louiza". Initially it is true.

while (notFound && someArray.length > 0) {
The loop continues only while

we have not found the name yet, and

the array still has elements (length > 0). This prevents an infinite loop if the name is not present at all.

if (someArray[0] === "Louiza") { ... }
Checks whether the first element of the array is "Louiza".

If found:

Logs "Found her!".

Sets notFound to false, which will stop the loop in the next condition check.

Otherwise:

someArray.shift(); removes the first element, so the next name moves to index 0 for the next iteration.

After the loop completes, console.log(notFound); prints false if the name was found, or true if the array was exhausted without finding it.

2.4 Generating the Fibonacci sequence with while

Example: create an array containing the first 25 values of the Fibonacci sequence.
let nr1 = 0;
let nr2 = 1;
let temp;
let fibonacciArray = [];
while (fibonacciArray.length < 25) {

fibonacciArray.push(nr1);

temp = nr1 + nr2;

nr1 = nr2;

nr2 = temp;

}

console.log(fibonacciArray);

Explanation:

nr1 and nr2 hold consecutive Fibonacci numbers, starting at 0 and 1.

temp is a temporary variable to store the next value in the sequence.

fibonacciArray starts as an empty array; we will fill it with Fibonacci numbers.

while (fibonacciArray.length < 25) {
Loops until the array contains 25 elements.

fibonacciArray.push(nr1); Appends the current nr1 to the array.

temp = nr1 + nr2; Computes the next Fibonacci number as the sum of the two previous ones.

nr1 = nr2; and nr2 = temp; Shift the pair forward: what was nr2 becomes the new nr1, and temp becomes the new nr2.

The resulting array starts 0, 1, 1, 2, 3, 5, ... and quickly grows large.

3. do...while Loop

3.1 Concept and Syntax

A do...while loop guarantees that its body is executed at least once, because the condition is checked after the body runs.

Syntax:
do {

// code to execute at least once

} while (condition);

Use this when you must perform the action at least once—typical scenarios include user input prompts or connection attempts.

3.2 Validating user input between 0 and 100

Example: repeatedly ask the user for a number in a valid range.
let number;
do {

number = prompt("Please enter a number between 0 and 100");

} while (!number || number < 0 || number > 100);

console.log("You entered:", number);

Explanation:

let number;
Declares a variable to hold the user’s input.
do { ... } while (...);
Ensures the prompt is shown at least once.

Inside the do block:

prompt("Please enter a number between 0 and 100") displays a dialog and returns a string typed by the user.

The result is assigned to number.

The while condition:

!number checks for an empty or cancel case.

number < 0 checks for too small values.

number > 100 checks for too large values. If any of these are true, the loop repeats and the user is prompted again.

Once the user enters a valid number, the loop exits and the final value is logged.

4. for Loop

4.1 Concept and general form

A for loop is a compact loop construct with three parts in its header:

for (initialization; condition; update) {

// code to execute each iteration

}

Execution order:

Execute initialization (once).

Evaluate condition. If false, exit the loop.

Execute the body.

Execute update.

Return to step 2.

4.2 Counting with for

Example: log numbers 0 through 9.
for (let i = 0; i < 10; i = i + 1) {

console.log(i);

}

Explanation:

let i = 0; (initialization)
Declares and initializes loop counter i to 0.

i < 10; (condition) The body executes only while i is less than 10.

i = i + 1 (update) Increments i by 1 after each iteration.

console.log(i);
Outputs the current value of i for each iteration.

4.3 Using for to build arrays

4.3.1 Array of integers 0 to 99

let arr = [];
for (let i = 0; i < 100; i = i + 1) {
  arr.push(i);

}

console.log(arr);

Explanation:

let arr = [];
Creates an empty array to store values.

The loop runs for i from 0 to 99.

arr.push(i);
Adds the current i to the end of arr in each iteration.

After the loop, arr contains 100 elements, from 0 to 99.

4.3.2 Array of even numbers from 0 to 98

let arr = [];
for (let i = 0; i < 100; i = i + 2) {
  arr.push(i);

}

console.log(arr);

Explanation:

Increments by 2 instead of 1, so i takes on values 0, 2, 4, ..., 98.

The result is an array of even numbers under 100.

5. Nested Loops

5.1 Concept

A nested loop is a loop inside another loop. For example:

Nested loops are commonly used for operating on two-dimensional data, such as tables, matrices, or arrays of arrays.

5.2 Creating an array of arrays with nested for loops

Example: build a 3×7 structure (3 rows, 7 columns), where each inner array contains the numbers 0 through 6.
let arrOfArrays = [];
for (let i = 0; i < 3; i = i + 1) {

arrOfArrays.push([]);

for (let j = 0; j < 7; j = j + 1) {

arrOfArrays[i].push(j);

}

}

console.log(arrOfArrays);
console.table(arrOfArrays);

Explanation:

let arrOfArrays = [];
Creates an empty array that will hold other arrays (rows).

Outer loop (for (let i = 0; i < 3; i = i + 1)) Runs 3 times, once for each row.

arrOfArrays.push([]); Adds a new empty inner array for each row.

Inner loop (for (let j = 0; j < 7; j = j + 1)) Runs 7 times per row to fill columns.

arrOfArrays[i].push(j); Appends the current j value (0–6) to the currently active row.

Resulting structure (conceptually):

[

[0, 1, 2, 3, 4, 5, 6],

[0, 1, 2, 3, 4, 5, 6],

[0, 1, 2, 3, 4, 5, 6]

]

console.table(arrOfArrays); displays this neatly in tabular form in supporting consoles.

6. Loops and Arrays

6.1 Looping over arrays with for

General pattern:

let arr = /* some array */;
for (let i = 0; i < arr.length; i = i + 1) {

// use arr[i]

}

The condition i < arr.length ensures that every valid index is visited exactly once and the loop stops after the last element.

6.2 Logging each array element

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {

console.log(names[i]);

}

Explanation:

The loop counter i runs from 0 to names.length - 1.

names[i] accesses the element at position i.

Every name in the array is logged once.

6.3 Modifying every element in an array

Example: prepend "hello " to each name.
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {

names[i] = "hello " + names[i];

}

console.log(names);

Explanation:

Inside the loop, names[i] is reassigned to a new string built by concatenating "hello " with the current value.

After the loop, the array contents are: "hello Chantal", "hello John", "hello Maxime", "hello Bobbi", "hello Jair".

6.4 Filtering or transforming with conditions

Example: remove names starting with "M" (using delete) and prepend "hello " to the others.
let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  if (names[i].startsWith("M")) {

delete names[i];

continue;

}

names[i] = "hello " + names[i];

}

console.log(names);

Explanation:

names[i].startsWith("M") checks if the current name begins with "M".

If it does:

delete names[i]; removes the property at index i, leaving a hole (an empty slot) rather than shifting elements.

continue; skips the rest of the current iteration and proceeds with the next iteration.

For all other names, "hello " is prepended.

The resulting array includes an “empty item” where the deleted element was, because delete does not reindex the array.

6.5 Infinite loop hazard when modifying array length

Problematic example (do not use):

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let i = 0; i < names.length; i = i + 1) {
  names.push("...");

}

Explanation:

Each iteration adds a new element to the array with names.push("...").

This increases names.length continuously.

Because i is always less than the ever-growing names.length, the loop never terminates, creating an infinite loop.

7. for...of Loop

7.1 Concept and syntax

The for...of loop iterates directly over the values of an iterable, such as an array.

Syntax:
for (let variableName of array) {

// code that uses variableName

}

Interpretation: “For each value in array, call it variableName and execute the body.”

Unlike the for loop with an index, for...of is designed for processing values and does not provide direct control to modify the array elements by index inside the loop body.

7.2 Example: logging array values

let names = ["Chantal", "John", "Maxime", "Bobbi", "Jair"];
for (let name of names) {

console.log(name);

}

Explanation:

let name of names
On each iteration, name is assigned the next value from the names array.
console.log(name);
Logs the current name.

The loop automatically stops after all values have been processed.

Key points:

No index variable is needed; the code is concise and readable.

Because you are iterating over values, this pattern is ideal for reading or sending data elsewhere, but not for in-place modification by index.

8. break and continue in Loops (Conceptual)

8.1 break

break immediately terminates the nearest enclosing loop and continues execution after the loop.

Useful when you find what you were searching for and do not want further iterations.

8.2 continue

continue skips the rest of the current iteration and moves directly to the next iteration’s condition check.

Useful for skipping certain elements (for example, filtering).

Example:
for (let i = 1; i <= 10; i++) {
    if (i === 6) {

        break; // stops the loop

    }

    console.log(i);

}

for (let i = 1; i <= 10; i++) {
    if (i === 6) {

        continue; // skips the current iteration

    }

    console.log(i);

}