JS Arrays
JavaScript Arrays: Ordered Lists and Zero-Based Indexing
A JavaScript array is an ordered, resizable list that stores multiple values inside a single variable. Each element sits at a numeric index starting at 0, and arrays can hold strings, numbers, objects, or even nested arrays.
Creating and Reading Arrays
Create arrays with square bracket literals [...] rather than new Array(). Bracket literals are shorter and avoid the confusing single-number trap where new Array(5) creates five empty slots instead of [5].
Read elements from the start with items[0] or from the end with items.at(-1) (ES2022). Checking items.length returns the total count of slots in the array.
Practical Array Basics Example
Using spread syntax [...arr] lets you copy or combine arrays without changing the original lists.
const languages = ["HTML", "CSS", "JavaScript"];
// Read first and last elements cleanly
console.log("First:", languages[0]);
console.log("Last:", languages.at(-1));
// Update by index and copy with spread
languages[1] = "Tailwind CSS";
const fullStack = [...languages, "Node.js", "PostgreSQL"];
console.log("Count:", fullStack.length);
console.log("Full stack:", fullStack);
console.log("Is Array:", Array.isArray(fullStack));
Common Mistakes to Avoid
- Using
typeof arrto detect arrays:typeof ["a"]returns"object". Always useArray.isArray(value)to confirm an array. - Creating sparse holes with high indexes: Assigning
list[10] = "x"on a 2-item array leaves 8undefinedempty slots in between. Usepush()or spread syntax instead. - Removing items with
delete arr[1]:deleteleaves anundefinedhole and keeps.lengthunchanged. Usesplice()orfilter().
Frequently Asked Questions
How do I empty a JavaScript array?
If using let, assign items = []. If you must keep the same const reference shared elsewhere, set items.length = 0.
Can a JavaScript array store mixed data types?
Yes, JavaScript arrays can hold strings, numbers, booleans, and objects together, though keeping uniform item types makes code easier to maintain.
What happens when I read an index that does not exist?
Reading items[99] on a 3-item array returns undefined instead of throwing an error.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.