✅ Using for loop
We can iterate array and access array elements using for loop.
Example : It is an example of for loop.
let a = ["HTML", "CSS", "JS"];
// Iterating through for loop
for (let i = 0; i < a.length; i++) {
console.log(a[i])
}HTML
CSS
JS✅ Array forEach( )
The forEach() method calls a function (a callback function) once for each array element.
Note that the function takes 3 arguments:
The item value
The item index
The array itself
Example 1 :
const numbers = [45, 4, 9, 16, 25];
numbers.forEach((value, index, array) => {
console.log("Value:", value, "Index:", index, "Array:", array);
console.log("-----------------------------------------------");
});Value: 45 Index: 0 Array: [ 45, 4, 9, 16, 25 ]
-----------------------------------------------
Value: 4 Index: 1 Array: [ 45, 4, 9, 16, 25 ]
-----------------------------------------------
Value: 9 Index: 2 Array: [ 45, 4, 9, 16, 25 ]
-----------------------------------------------
Value: 16 Index: 3 Array: [ 45, 4, 9, 16, 25 ]
-----------------------------------------------
Value: 25 Index: 4 Array: [ 45, 4, 9, 16, 25 ]
-----------------------------------------------Example 2 :
let a = [12,13,14];
a.forEach(function (value) {
console.log(value);
});This example uses only the value parameter.
value is the current element of the array during each iteration. It is the value from the array a
12
13
14✅ Array map( )
The
map()method creates a new array by performing a function on each array element.The
map()method does not execute the function for array elements without values.The
map()method does not change the original array.
Example :
This example multiplies each array value by 2:
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map((value) => value * 2);
console.log(numbers2)[ 90, 8, 18, 32, 50 ]✅ Array filter( )
The filter() method creates a new array with array elements that pass a test.
Example : This example creates a new array from elements with a value larger than 18:
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter((value) => value > 18);
console.log(over18)[ 45, 25 ]✅ Array reduce( )
The
reduce()method runs a function on each array element to produce a single value.The
reduce()method works from left-to-right in the array.
Note that the function takes 4 arguments:
The array itself
The item index
The total (the initial value / previously returned value)
The item value
Example : This example finds the sum of all numbers in an array
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce((total, value, index, array) => total + value);
console.log(sum)99✅ Array every( )
The
every()method checks if all array values pass a test.The function takes 3 arguments:
The array itself
The item value
The item index
Example : This example checks if all array values are larger than 18
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every((value) => value > 18);
console.log("all Over 18 is " + allOver18);all Over 18 is false✅ Array some()
The some() method checks if some array values pass a test.
The function takes 3 arguments:
The array itself
The item value
The item index
Example : This example checks if some array values are larger than 18
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some((value) => value > 18);
console.log("some Over 18 is " + someOver18);some Over 18 is true✅ Array find( )
The
find()method returns the first element in the array that passes a test.It stops searching after finding the first match.
If no element satisfies the condition, it returns
undefined.
Example: This example finds the first number greater than 18
const numbers = [45, 4, 9, 16, 25];
let firstOver18 = numbers.find((value) => value > 18);
console.log("First Over 18 is " + firstOver18);First Over 18 is 45✅ Array.from( )
The Array.from() method returns an Array object from:
Any iterable object
Any object with a length property. In this example, we will be using Array from( ) method to create an array from the string value.
console.log(Array.from("Codeveda"));
console.log(Array.from([1, 2, 3], (x) => x + x));[
'C', 'o', 'd',
'e', 'v', 'e',
'd', 'a'
]
[ 2, 4, 6 ]✅ Array with( ) Method
The Array with( ) method as a safe way to update elements in an array without altering the original array.
Example :
const months = ["January", "February", "Mar", "April"];
const myMonths = months.with(2, "March");
console.log(myMonths);[ 'January', 'February', 'March', 'April' ]✅ Array Spread (...)
The ... operator expands an array into individual elements.
Example : This can be used join arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);1,2,3,4,5,6✅ Array Rest Operator (...)
The rest operator looks just like the spread operator (...), but it's used in destructuring to collect the remaining (or "rest") elements into a new array.
const fruits = ["apple", "banana", "mango", "orange"];
const [first, second, ...rest] = fruits;
console.log(first, second, rest); apple banana [ 'mango', 'orange' ]✅ Array splice( )
The
splice()method adds or removes elements from an array.It modifies the original array.
Syntax:
array.splice(startIndex, deleteCount, item1, item2, ...)
Example: This example removes 2 items starting from index 2 and adds two new items.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
console.log(fruits);["Banana", "Orange", "Lemon", "Kiwi"]✅ Array slice( )
The
slice()method returns a shallow copy of a portion of an array.It does not modify the original array.
Syntax:
array.slice(startIndex, endIndex)(endIndex is not included)
Example: This example creates a new array from index 1 to 3 (excluding 3)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
console.log(citrus);["Orange", "Apple"]<div class="infographic-arriter">
<style>
.infographic-arriter {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', -apple-system, sans-serif;
--mono-font: 'IBM Plex Mono', 'Courier New', monospace;
margin: 0 auto;
box-sizing: border-box;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-arriter[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--ok: #5cd6a0;
--ok-soft: #16342a;
}
.infographic-arriter * { box-sizing: border-box; }
.infographic-arriter .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-arriter .ig-title {
font-family: var(--display-font); font-size: clamp(1.4rem, 4.5vw, 1.9rem);
font-weight: 600; text-align: center; margin: 0 0 1.25rem;
}
.infographic-arriter .tabs { display: flex; gap: 0.4rem; justify-content: center; flex-wrap: wrap; }
.infographic-arriter .tab {
font: inherit; font-size: 0.76rem; font-weight: 600; border: 1px solid var(--line);
background: var(--paper); color: var(--ink-soft); padding: 0.38rem 0.75rem;
border-radius: 999px; cursor: pointer;
}
.infographic-arriter .tab.is-active { background: var(--accent); color: #fff; border-color: var(--accent); }
.infographic-arriter .chips { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
.infographic-arriter .chip {
font: inherit; font-size: 0.78rem; font-weight: 700; font-family: var(--mono-font);
border: 1px solid var(--line); background: var(--paper-alt); color: var(--ink);
padding: 0.4rem 0.75rem; border-radius: 6px; cursor: pointer;
}
.infographic-arriter .chip.is-active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.infographic-arriter .playground {
margin-top: 1.5rem; background: var(--paper-alt); border: 1px solid var(--line); padding: 1.25rem 1rem;
}
.infographic-arriter .inputs-row { display: flex; flex-wrap: wrap; gap: 0.7rem; justify-content: center; }
.infographic-arriter .field { position: relative; display: flex; flex-direction: column; align-items: center; }
.infographic-arriter .field-tag { font-size: 0.62rem; font-family: var(--mono-font); color: var(--accent); margin-bottom: 0.3rem; }
.infographic-arriter .field input {
height: 2.3rem; font-family: var(--mono-font); font-size: 0.82rem; text-align: center;
border: 1px solid var(--line); background: var(--paper); color: var(--ink); border-radius: 5px; outline: none;
padding: 0 0.5rem;
}
.infographic-arriter .field input:focus { border-color: var(--accent); }
.infographic-arriter .field.wide input { width: 13rem; }
.infographic-arriter .field.narrow input { width: 4.4rem; }
.infographic-arriter .run-row { display: flex; justify-content: center; margin-top: 1rem; }
.infographic-arriter .run-btn {
font: inherit; font-size: 0.85rem; font-weight: 700; border: none; background: var(--accent);
color: #fff; padding: 0.55rem 1.3rem; border-radius: 999px; cursor: pointer;
}
.infographic-arriter .run-btn:hover { opacity: 0.9; }
.infographic-arriter .run-btn:disabled { opacity: 0.5; cursor: default; }
.infographic-arriter .call-line {
font-family: var(--mono-font); font-size: 0.82rem; text-align: center; font-weight: 700;
padding: 0.55rem 0.8rem; border-radius: 6px; margin-top: 1.1rem;
background: var(--accent-soft); color: var(--accent); border: 1px solid var(--accent);
word-break: break-word; white-space: pre-wrap;
}
.infographic-arriter .result-single { display: flex; justify-content: center; margin-top: 0.9rem; }
.infographic-arriter .result-box {
font-family: var(--mono-font); font-size: 0.9rem; font-weight: 700;
padding: 0.5rem 1.1rem; background: var(--ok-soft); color: var(--ok); border: 1px solid var(--ok);
border-radius: 6px; min-width: 6rem; text-align: center; word-break: break-word;
box-shadow: 0 3px 8px rgba(0,0,0,0.1);
}
.infographic-arriter .result-lines { margin-top: 0.9rem; display: grid; gap: 0.35rem; }
.infographic-arriter .result-line-item {
font-family: var(--mono-font); font-size: 0.8rem; text-align: center;
padding: 0.35rem 0.6rem; background: var(--ok-soft); color: var(--ok); border: 1px solid var(--ok);
border-radius: 5px; opacity: 0; transform: translateY(-6px); transition: opacity 0.3s ease, transform 0.3s ease;
}
.infographic-arriter .result-line-item.is-in { opacity: 1; transform: translateY(0); }
.infographic-arriter .caption {
text-align: center; font-size: 0.8rem; color: var(--ink-soft); margin-top: 1rem; min-height: 1.2em;
}
@media (prefers-reduced-motion: reduce) {
.infographic-arriter *, .infographic-arriter *::before, .infographic-arriter *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<h2 class="ig-title">Array Iteration Playground</h2>
<div class="tabs" id="tabs"></div>
<div class="chips" id="chips"></div>
<div class="playground">
<div class="inputs-row" id="inputsRow"></div>
<div class="run-row"><button class="run-btn" id="runBtn">▶ Run</button></div>
<div class="call-line" id="callLine"></div>
<div class="result-single" id="resultSingle" style="display:none;"><div class="result-box" id="resultBox"></div></div>
<div class="result-lines" id="resultLines" style="display:none;"></div>
</div>
<p class="caption" id="caption"></p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-arriter')
|| document.querySelector('.infographic-arriter');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
function parseList(str) {
return (str || '').split(',').map(s => s.trim()).filter(s => s !== '').map(s => {
const n = Number(s);
return (s !== '' && !isNaN(n)) ? n : s;
});
}
function fmtVal(v) {
if (v === undefined) return 'undefined';
if (typeof v === 'string') return `'${v}'`;
return String(v);
}
function fmtArr(arr) {
return '[ ' + arr.map(fmtVal).join(', ') + ' ]';
}
function arrWith(arr, i, v) {
const copy = arr.slice();
copy[i] = v;
return copy;
}
const CATEGORIES = {
'Iterate': [
{
id: 'forLoop', label: 'for loop',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: 'HTML, CSS, JS' }],
call: v => `for (let i = 0; i < a.length; i++) console.log(a[i]);`,
multiline: true,
run: v => parseList(v.arr).map(x => String(x)),
caption: 'runs once per element, in order'
},
{
id: 'forEach', label: 'forEach()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }],
call: v => `a.forEach((value, index) => console.log(value, index));`,
multiline: true,
run: v => parseList(v.arr).map((x, i) => `Value: ${x} Index: ${i}`),
caption: 'same idea, as a method with a callback'
}
],
'Transform': [
{
id: 'map', label: 'map()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }, { key: 'mult', tag: '× by', narrow: true, default: '2' }],
call: v => `a.map(value => value * ${v.mult})`,
run: v => fmtArr(parseList(v.arr).map(x => Number(x) * Number(v.mult))),
caption: 'creates a new array — original stays the same'
},
{
id: 'filter', label: 'filter()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }, { key: 'gt', tag: 'value >', narrow: true, default: '18' }],
call: v => `a.filter(value => value > ${v.gt})`,
run: v => fmtArr(parseList(v.arr).filter(x => Number(x) > Number(v.gt))),
caption: 'keeps only elements that pass the test'
},
{
id: 'reduce', label: 'reduce()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }],
call: v => `a.reduce((total, value) => total + value)`,
run: v => String(parseList(v.arr).reduce((t, x) => Number(t) + Number(x))),
caption: 'combines every element into a single value'
}
],
'Test': [
{
id: 'every', label: 'every()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }, { key: 'gt', tag: 'value >', narrow: true, default: '18' }],
call: v => `a.every(value => value > ${v.gt})`,
run: v => String(parseList(v.arr).every(x => Number(x) > Number(v.gt))),
caption: 'true only if every element passes'
},
{
id: 'some', label: 'some()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }, { key: 'gt', tag: 'value >', narrow: true, default: '18' }],
call: v => `a.some(value => value > ${v.gt})`,
run: v => String(parseList(v.arr).some(x => Number(x) > Number(v.gt))),
caption: 'true if at least one element passes'
},
{
id: 'find', label: 'find()',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '45, 4, 9, 16, 25' }, { key: 'gt', tag: 'value >', narrow: true, default: '18' }],
call: v => `a.find(value => value > ${v.gt})`,
run: v => { const r = parseList(v.arr).find(x => Number(x) > Number(v.gt)); return r === undefined ? 'undefined' : String(r); },
caption: 'returns the first match, then stops'
}
],
'Create': [
{
id: 'fromString', label: 'Array.from(string)',
inputs: [{ key: 'str', tag: 'string', wide: true, default: 'Codeveda' }],
call: v => `Array.from("${v.str}")`,
run: v => fmtArr(Array.from(v.str)),
caption: 'turns any iterable into a real array'
},
{
id: 'fromMap', label: 'Array.from(map fn)',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: '1, 2, 3' }],
call: v => `Array.from(a, x => x + x)`,
run: v => fmtArr(Array.from(parseList(v.arr), x => Number(x) + Number(x))),
caption: 'builds a new array while transforming each item'
}
],
'Combine': [
{
id: 'spread', label: '...spread',
inputs: [{ key: 'a1', tag: 'array 1', default: '1, 2, 3' }, { key: 'a2', tag: 'array 2', default: '4, 5, 6' }],
call: v => `[...a1, ...a2]`,
run: v => fmtArr([...parseList(v.a1), ...parseList(v.a2)]),
caption: 'expands both arrays into one'
},
{
id: 'rest', label: '...rest',
inputs: [{ key: 'arr', tag: 'array', wide: true, default: 'apple, banana, mango, orange' }],
call: v => `const [first, second, ...rest] = a;`,
multiline: true,
run: v => {
const [first, second, ...rest] = parseList(v.arr);
return [`first = ${fmtVal(first)}`, `second = ${fmtVal(second)}`, `rest = ${fmtArr(rest)}`];
},
caption: 'grabs the first items, collects the remainder'
}
],
'Modify & Extract': [
{
id: 'splice', label: 'splice()',
inputs: [
{ key: 'arr', tag: 'array', wide: true, default: 'Banana, Orange, Apple, Mango' },
{ key: 'start', tag: 'start', narrow: true, default: '2' },
{ key: 'del', tag: 'delete count', narrow: true, default: '2' },
{ key: 'items', tag: 'insert', default: 'Lemon, Kiwi' }
],
multiline: true,
call: v => `a.splice(${v.start}, ${v.del}, ${parseList(v.items).map(x => `"${x}"`).join(', ')})`,
run: v => {
const copy = parseList(v.arr);
const inserted = parseList(v.items);
const removed = copy.splice(Number(v.start), Number(v.del), ...inserted);
return [`removed: ${fmtArr(removed)}`, `array is now: ${fmtArr(copy)}`];
},
caption: 'mutates the original array in place'
},
{
id: 'slice', label: 'slice()',
inputs: [
{ key: 'arr', tag: 'array', wide: true, default: 'Banana, Orange, Apple, Mango' },
{ key: 'start', tag: 'start', narrow: true, default: '1' },
{ key: 'end', tag: 'end', narrow: true, default: '3' }
],
call: v => `a.slice(${v.start}, ${v.end})`,
run: v => fmtArr(parseList(v.arr).slice(Number(v.start), Number(v.end))),
caption: 'copies a portion — original is untouched'
},
{
id: 'with', label: 'with()',
inputs: [
{ key: 'arr', tag: 'array', wide: true, default: 'January, February, Mar, April' },
{ key: 'idx', tag: 'index', narrow: true, default: '2' },
{ key: 'val', tag: 'new value', default: 'March' }
],
multiline: true,
call: v => `a.with(${v.idx}, "${v.val}")`,
run: v => {
const original = parseList(v.arr);
const updated = arrWith(original, Number(v.idx), v.val);
return [`new array: ${fmtArr(updated)}`, `original unchanged: ${fmtArr(original)}`];
},
caption: 'a safe update that never touches the original'
}
]
};
const tabsEl = wrapper.querySelector('#tabs');
const chipsEl = wrapper.querySelector('#chips');
const inputsRow = wrapper.querySelector('#inputsRow');
const callLine = wrapper.querySelector('#callLine');
const resultSingle = wrapper.querySelector('#resultSingle');
const resultBox = wrapper.querySelector('#resultBox');
const resultLines = wrapper.querySelector('#resultLines');
const caption = wrapper.querySelector('#caption');
let currentCategory = 'Iterate';
let currentMethod = CATEGORIES.Iterate[0];
let values = {};
function updatePreview() {
callLine.textContent = currentMethod.call(values);
caption.textContent = currentMethod.caption;
}
function hideResults() {
resultSingle.style.display = 'none';
resultLines.style.display = 'none';
}
function runNow() {
let result;
try { result = currentMethod.run(values); } catch (e) { result = 'Error'; }
callLine.textContent = currentMethod.call(values);
if (currentMethod.multiline) {
resultSingle.style.display = 'none';
resultLines.style.display = 'grid';
resultLines.innerHTML = '';
const lines = Array.isArray(result) ? result : [String(result)];
const els = lines.map(line => {
const el = document.createElement('div');
el.className = 'result-line-item';
el.textContent = line;
resultLines.appendChild(el);
return el;
});
const runBtnEl = wrapper.querySelector('#runBtn');
runBtnEl.disabled = true;
els.forEach((el, i) => {
setTimeout(() => {
el.classList.add('is-in');
if (i === els.length - 1) runBtnEl.disabled = false;
}, 220 * i);
});
} else {
resultLines.style.display = 'none';
resultSingle.style.display = 'flex';
resultBox.textContent = result;
}
}
function buildInputs() {
inputsRow.innerHTML = '';
values = {};
currentMethod.inputs.forEach(spec => {
values[spec.key] = spec.default;
const field = document.createElement('div');
field.className = 'field' + (spec.wide ? ' wide' : '') + (spec.narrow ? ' narrow' : '');
const tag = document.createElement('span');
tag.className = 'field-tag';
tag.textContent = spec.tag;
const input = document.createElement('input');
input.type = 'text';
input.value = spec.default;
input.addEventListener('input', () => { values[spec.key] = input.value; updatePreview(); });
field.appendChild(tag);
field.appendChild(input);
inputsRow.appendChild(field);
});
updatePreview();
hideResults();
}
function selectMethod(method) {
currentMethod = method;
wrapper.querySelectorAll('.chip').forEach(c => c.classList.toggle('is-active', c.dataset.id === method.id));
buildInputs();
}
const runBtn = wrapper.querySelector('#runBtn');
runBtn.addEventListener('click', runNow);
function buildChips() {
chipsEl.innerHTML = '';
CATEGORIES[currentCategory].forEach((m, idx) => {
const chip = document.createElement('button');
chip.className = 'chip';
chip.textContent = m.label;
chip.dataset.id = m.id;
chip.addEventListener('click', () => selectMethod(m));
chipsEl.appendChild(chip);
if (idx === 0) selectMethod(m);
});
}
function selectCategory(name) {
currentCategory = name;
wrapper.querySelectorAll('.tab').forEach(t => t.classList.toggle('is-active', t.dataset.cat === name));
buildChips();
}
Object.keys(CATEGORIES).forEach(name => {
const tab = document.createElement('button');
tab.className = 'tab';
tab.textContent = name;
tab.dataset.cat = name;
tab.addEventListener('click', () => selectCategory(name));
tabsEl.appendChild(tab);
});
selectCategory('Iterate');
})();
</script>.demo {
font-family: system-ui, sans-serif;
padding: 16px;
}
.demo h1 {
color: #2563eb;
margin: 0 0 8px;
}
.demo p {
color: #4b5563;
margin: 0;
}document.querySelector('.demo h1')?.addEventListener('click', () => {
alert('Hello from live preview!');
});