✅ Accessing Array Elements
Any element in the array can be accessed using the index number. The index in the arrays starts with 0.
let a = ["HTML", "CSS", "JS"];
console.log(a[0]); //HTML
console.log(a[1]); //CSS📌Accessing the First Element of an Array
The array indexing starts from 0, so we can access first element of array using the index number.
let a = ["HTML", "CSS", "JS"];
let first = a[0];
console.log("First Item: ", first); //First Item: HTML♦️Accessing the Last Element of an Array
We can access the last array element using [array.length - 1] index number.
let a = ["HTML", "CSS", "JS"];
let last = a[a.length - 1];
console.log("Last Item: ", last); // Last Item: JS⚡Modifying the Array Elements
Elements in an array can be modified by assigning a new value to their corresponding index.
let a = ["HTML", "CSS", "JS"];
console.log(a); //[ 'HTML', 'CSS', 'JS' ]
a[1]= "Bootstrap";
console.log(a); //[ 'HTML', 'Bootstrap', 'JS' ]✍️ Adding Elements to the Array
Elements can be added to the array using methods like push( ) and unshift( ).
The push( ) method add the element to the end of the array.
The unshift( ) method add the element to the starting of the array.
Example :
let a = ["HTML", "CSS", "JS"];
a.push("Node.js");
a.unshift("Web Development");
console.log(a); //[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]📍Removing Elements from an Array
To remove the elements from an array we have different methods like pop( ), shift( ), or splice( ).
The pop( ) method removes an element from the last index of the array.
The shift( ) method removes the element from the first index of the array.
The splice( ) method removes or replaces the element from the array.
let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a);
// Original Array: HTML,CSS,JS
let lst = a.pop();
console.log("After Removing the last: " + a);
// After Removing the last: HTML,CSS
let fst = a.shift();
console.log("After Removing the First: " + a);
// After Removing the First: CSS
a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a);
// After Removing 2 elements starting from index 1: CSS➡️ Array Length
We can get the length of the array using the array length property.
let a = ["HTML", "CSS", "JS"];
let len = a.length;
console.log("Array Length: " + len); //Array Length: 3🖋️ Increase and Decrease the Array Length
We can increase and decrease the array length using the JavaScript length property.
let a = ["HTML", "CSS", "JS"]
a.length = 7;
console.log("After Increasing Length: ", a);
// After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ]
a.length = 2;
console.log("After Decreasing Length: ", a)
// After Decreasing Length: [ 'HTML', 'CSS' ]<div class="infographic-arrplay">
<style>
.infographic-arrplay {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--line: #ddd6c9;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--warn: #b45309;
--warn-soft: #fdf0dc;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--bad: #b42318;
--bad-soft: #fbe9e7;
--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-arrplay[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--line: #2c313d;
--accent: #5b8def;
--accent-soft:#202942;
--warn: #e0a458;
--warn-soft: #3a2c14;
--ok: #5cd6a0;
--ok-soft: #16342a;
--bad: #e57373;
--bad-soft: #3a2222;
}
.infographic-arrplay * { box-sizing: border-box; }
.infographic-arrplay .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-arrplay .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.5rem;
}
/* Persistent array visual */
.infographic-arrplay .array-scroll { overflow-x: auto; padding: 0.3rem 0 0.5rem; }
.infographic-arrplay .array-row { display: flex; gap: 0.5rem; justify-content: center; min-width: min-content; }
.infographic-arrplay .slot { display: flex; flex-direction: column; align-items: center; }
.infographic-arrplay .elbox {
min-width: 3.6rem; height: 3rem; padding: 0 0.6rem; border-radius: 8px; display: flex; align-items: center; justify-content: center;
font-family: var(--mono-font); font-size: 0.82rem; font-weight: 700;
border: 2px solid var(--warn); background: var(--warn-soft); color: var(--warn);
transition: transform 0.2s ease, opacity 0.2s ease; white-space: nowrap;
}
.infographic-arrplay .elbox.empty { border-style: dashed; background: var(--paper); color: var(--ink-soft); font-weight: 400; opacity: 0.6; }
.infographic-arrplay .elbox.is-active { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); box-shadow: 0 3px 8px rgba(0,0,0,0.1); }
.infographic-arrplay .elbox.pop-in { animation: ap-pop 0.35s ease; }
.infographic-arrplay .elbox.pop-out { animation: ap-out 0.3s ease forwards; }
@keyframes ap-pop { 0% { transform: scale(0.4); opacity: 0; } 60% { transform: scale(1.1); } 100% { transform: scale(1); opacity: 1; } }
@keyframes ap-out { 0% { transform: scale(1); opacity: 1; } 100% { transform: scale(0.4); opacity: 0; } }
.infographic-arrplay .idx-num { font-size: 0.72rem; color: var(--ink-soft); margin-top: 0.35rem; font-family: var(--mono-font); }
.infographic-arrplay .array-empty-msg { text-align: center; color: var(--ink-soft); font-family: var(--mono-font); font-size: 0.85rem; padding: 0.6rem; }
.infographic-arrplay .reset-row { display: flex; justify-content: center; margin: 0.75rem 0 1.5rem; }
.infographic-arrplay .reset-btn {
font: inherit; font-size: 0.78rem; font-weight: 700; font-family: var(--mono-font); border: 1px solid var(--line);
background: transparent; color: var(--ink-soft); padding: 0.35rem 0.85rem; border-radius: 999px; cursor: pointer;
}
.infographic-arrplay .reset-btn:hover { border-color: var(--accent); color: var(--accent); }
/* Tabs + chips */
.infographic-arrplay .tabs { display: flex; gap: 0.4rem; justify-content: center; flex-wrap: wrap; }
.infographic-arrplay .tab {
font: inherit; font-size: 0.78rem; font-weight: 600; border: 1px solid var(--line);
background: var(--paper); color: var(--ink-soft); padding: 0.4rem 0.8rem;
border-radius: 999px; cursor: pointer;
}
.infographic-arrplay .tab.is-active { background: var(--accent); color: #fff; border-color: var(--accent); }
.infographic-arrplay .chips { display: flex; flex-wrap: wrap; gap: 0.5rem; justify-content: center; margin-top: 1rem; }
.infographic-arrplay .chip {
font: inherit; font-size: 0.8rem; font-weight: 700; font-family: var(--mono-font);
border: 1px solid var(--line); background: var(--paper-alt); color: var(--ink);
padding: 0.4rem 0.8rem; border-radius: 6px; cursor: pointer;
}
.infographic-arrplay .chip.is-active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.infographic-arrplay .playground {
margin-top: 1.5rem; background: var(--paper-alt); border: 1px solid var(--line); padding: 1.25rem 1rem;
}
.infographic-arrplay .inputs-row { display: flex; flex-wrap: wrap; gap: 0.7rem; justify-content: center; }
.infographic-arrplay .field { position: relative; display: flex; flex-direction: column; align-items: center; }
.infographic-arrplay .field-tag { font-size: 0.62rem; font-family: var(--mono-font); color: var(--accent); margin-bottom: 0.3rem; }
.infographic-arrplay .field input {
height: 2.3rem; font-family: var(--mono-font); font-size: 0.85rem; text-align: center;
border: 1px solid var(--line); background: var(--paper); color: var(--ink); border-radius: 5px; outline: none;
padding: 0 0.5rem; width: 7.5rem;
}
.infographic-arrplay .field input:focus { border-color: var(--accent); }
.infographic-arrplay .field.narrow input { width: 4.2rem; }
.infographic-arrplay .run-row { display: flex; justify-content: center; margin-top: 1rem; }
.infographic-arrplay .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-arrplay .run-btn:hover { opacity: 0.9; }
.infographic-arrplay .call-line {
font-family: var(--mono-font); font-size: 0.85rem; 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;
}
.infographic-arrplay .result-line {
text-align: center; font-family: var(--mono-font); font-size: 0.85rem; margin-top: 0.7rem;
color: var(--ink-soft); min-height: 1.3em;
}
.infographic-arrplay .result-line strong { color: var(--ok); }
.infographic-arrplay .result-line.is-error strong { color: var(--bad); }
.infographic-arrplay .caption {
text-align: center; font-size: 0.82rem; color: var(--ink-soft); margin-top: 0.75rem; min-height: 1.2em;
}
.infographic-arrplay .caption strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-arrplay *, .infographic-arrplay *::before, .infographic-arrplay *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<h2 class="ig-title">Array Methods Playground</h2>
<div class="array-scroll"><div class="array-row" id="arrayRow"></div></div>
<div class="reset-row"><button class="reset-btn" id="resetBtn">⟲ Reset array</button></div>
<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-line" id="resultLine"></div>
</div>
<p class="caption" id="caption"></p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-arrplay')
|| document.querySelector('.infographic-arrplay');
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');
const INITIAL = ['HTML', 'CSS', 'JS'];
let a = INITIAL.slice();
const arrayRow = wrapper.querySelector('#arrayRow');
const resetBtn = wrapper.querySelector('#resetBtn');
const tabsEl = wrapper.querySelector('#tabs');
const chipsEl = wrapper.querySelector('#chips');
const inputsRow = wrapper.querySelector('#inputsRow');
const runBtn = wrapper.querySelector('#runBtn');
const callLine = wrapper.querySelector('#callLine');
const resultLine = wrapper.querySelector('#resultLine');
const caption = wrapper.querySelector('#caption');
function fmtVal(v) {
if (v === undefined) return '<empty>';
if (typeof v === 'string') return `"${v}"`;
return String(v);
}
function fmtArray() {
if (a.length === 0) return '[ ]';
return '[ ' + Array.from({ length: a.length }, (_, i) =>
Object.prototype.hasOwnProperty.call(a, i) ? fmtVal(a[i]) : '<empty>'
).join(', ') + ' ]';
}
function renderArray(activeIndex) {
arrayRow.innerHTML = '';
if (a.length === 0) {
const msg = document.createElement('div');
msg.className = 'array-empty-msg';
msg.textContent = 'the array is empty';
arrayRow.appendChild(msg);
return;
}
for (let i = 0; i < a.length; i++) {
const slot = document.createElement('div');
slot.className = 'slot';
const box = document.createElement('div');
const has = Object.prototype.hasOwnProperty.call(a, i);
box.className = 'elbox' + (!has ? ' empty' : '') + (activeIndex === i ? ' is-active' : '');
box.textContent = has ? a[i] : '';
slot.appendChild(box);
const idx = document.createElement('div');
idx.className = 'idx-num';
idx.textContent = i;
slot.appendChild(idx);
arrayRow.appendChild(slot);
}
}
const CATEGORIES = {
'Access': [
{
id: 'index', label: 'a[index]',
inputs: [{ key: 'i', tag: 'index', narrow: true, default: '0' }],
call: v => `a[${v.i}]`,
run: v => {
const i = Number(v.i);
const inRange = i >= 0 && i < a.length;
if (!inRange) {
return { activeIndex: undefined, error: true, msg: `index ${i} is out of range — a[${i}] is undefined` };
}
return { activeIndex: i, result: a[i], msg: `a[${v.i}] is ${fmtVal(a[i])}` };
}
},
{
id: 'first', label: 'first element',
inputs: [],
call: () => `a[0]`,
run: () => ({ activeIndex: 0, result: a[0], msg: `first element is ${fmtVal(a[0])}` })
},
{
id: 'last', label: 'last element',
inputs: [],
call: () => `a[a.length - 1]`,
run: () => ({ activeIndex: a.length - 1, result: a[a.length - 1], msg: `last element is ${fmtVal(a[a.length - 1])}` })
}
],
'Modify': [
{
id: 'set', label: 'a[index] = value',
inputs: [{ key: 'i', tag: 'index', narrow: true, default: '1' }, { key: 'val', tag: 'new value', default: 'Bootstrap' }],
call: v => `a[${v.i}] = "${v.val}"`,
run: v => { const i = Number(v.i); a[i] = v.val; return { activeIndex: i, msg: `a[${i}] is now "${v.val}"` }; }
}
],
'Add': [
{
id: 'push', label: 'push()',
inputs: [{ key: 'val', tag: 'value', default: 'Node.js' }],
call: v => `a.push("${v.val}")`,
run: v => { a.push(v.val); return { activeIndex: a.length - 1, justAdded: a.length - 1, msg: `added to the end — length is now ${a.length}` }; }
},
{
id: 'unshift', label: 'unshift()',
inputs: [{ key: 'val', tag: 'value', default: 'Web Development' }],
call: v => `a.unshift("${v.val}")`,
run: v => { a.unshift(v.val); return { activeIndex: 0, justAdded: 0, msg: `added to the start — length is now ${a.length}` }; }
}
],
'Remove': [
{
id: 'pop', label: 'pop()',
inputs: [],
call: () => `a.pop()`,
run: () => { const removed = a.pop(); return { msg: `removed ${fmtVal(removed)} from the end` }; }
},
{
id: 'shift', label: 'shift()',
inputs: [],
call: () => `a.shift()`,
run: () => { const removed = a.shift(); return { msg: `removed ${fmtVal(removed)} from the start` }; }
},
{
id: 'splice', label: 'splice()',
inputs: [{ key: 'start', tag: 'start', narrow: true, default: '1' }, { key: 'count', tag: 'count', narrow: true, default: '2' }],
call: v => `a.splice(${v.start}, ${v.count})`,
run: v => { const removed = a.splice(Number(v.start), Number(v.count)); return { msg: `removed ${removed.length ? removed.map(fmtVal).join(', ') : 'nothing'}` }; }
}
],
'Length': [
{
id: 'getLength', label: 'a.length',
inputs: [],
call: () => `a.length`,
run: () => ({ msg: `a.length is ${a.length}` })
},
{
id: 'setLength', label: 'a.length = n',
inputs: [{ key: 'n', tag: 'new length', narrow: true, default: '7' }],
call: v => `a.length = ${v.n}`,
run: v => { a.length = Math.max(0, Number(v.n)); return { msg: `array length is now ${a.length}` }; }
}
]
};
let currentCategory = 'Access';
let currentMethod = CATEGORIES.Access[0];
let values = {};
function buildInputs() {
inputsRow.innerHTML = '';
values = {};
currentMethod.inputs.forEach(spec => {
values[spec.key] = spec.default;
const field = document.createElement('div');
field.className = 'field' + (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();
}
function updatePreview() {
callLine.textContent = currentMethod.call(values);
}
function selectMethod(method) {
currentMethod = method;
wrapper.querySelectorAll('.chip').forEach(c => c.classList.toggle('is-active', c.dataset.id === method.id));
buildInputs();
resultLine.textContent = '';
}
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);
});
runBtn.addEventListener('click', () => {
const outcome = currentMethod.run(values);
renderArray(outcome.activeIndex);
if (outcome.justAdded !== undefined) {
const boxes = arrayRow.querySelectorAll('.elbox');
if (boxes[outcome.justAdded]) boxes[outcome.justAdded].classList.add('pop-in');
}
resultLine.className = 'result-line' + (outcome.error ? ' is-error' : '');
resultLine.innerHTML = `→ <strong>${outcome.msg}</strong>`;
caption.innerHTML = `array is now <strong>${fmtArray()}</strong>`;
});
resetBtn.addEventListener('click', () => {
a = INITIAL.slice();
renderArray(null);
resultLine.textContent = '';
caption.innerHTML = `array reset to <strong>${fmtArray()}</strong>`;
});
renderArray(null);
selectCategory('Access');
caption.innerHTML = `array is <strong>${fmtArray()}</strong>`;
})();
</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!');
});