惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Spread Privacy
Spread Privacy
A
About on SuperTechFans
NISL@THU
NISL@THU
The GitHub Blog
The GitHub Blog
Hugging Face - Blog
Hugging Face - Blog
S
Security @ Cisco Blogs
S
SegmentFault 最新的问题
G
Google Developers Blog
B
Blog
N
News and Events Feed by Topic
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
V2EX - 技术
V2EX - 技术
V
Visual Studio Blog
MyScale Blog
MyScale Blog
Webroot Blog
Webroot Blog
Vercel News
Vercel News
IT之家
IT之家
Microsoft Security Blog
Microsoft Security Blog
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
S
Security Affairs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
博客园 - 叶小钗
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
T
Tailwind CSS Blog
F
Fortinet All Blogs
D
DataBreaches.Net
博客园 - Franky
博客园_首页
H
Heimdal Security Blog
宝玉的分享
宝玉的分享
阮一峰的网络日志
阮一峰的网络日志
Attack and Defense Labs
Attack and Defense Labs
Project Zero
Project Zero
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
JavaScript Arrays 101
Pratham · 2026-05-10 · via DEV Community

Your first real data structure — and the one you'll use more than any other.


Let me paint a picture. You're building a to-do app. You've got 5 tasks. So you do the "logical" thing:

let task1 = "Buy groceries";
let task2 = "Finish homework";
let task3 = "Call mom";
let task4 = "Go to gym";
let task5 = "Read a chapter";

Enter fullscreen mode Exit fullscreen mode

Five variables for five tasks. Now imagine you have 50 tasks. Or 500. Are you going to create 500 separate variables? Obviously not. That's insane. And even with just 5, how do you loop through them? How do you add a new one? How do you remove one?

This is exactly the problem arrays solve. And once you get comfortable with them, you'll wonder how you ever wrote JavaScript without them.


What Is an Array?

An array is an ordered collection of values stored under a single variable name. Instead of creating a separate variable for each value, you put them all in one place — like a numbered list.

Think of it as a row of lockers. Each locker has a number (its index) and can hold one item (a value). You can look at any locker, change what's inside, or walk down the entire row checking each one.

┌─────────┬─────────┬─────────┬─────────┬─────────┐
│  Index 0│  Index 1│  Index 2│  Index 3│  Index 4│
├─────────┼─────────┼─────────┼─────────┼─────────┤
│ "Buy    │ "Finish │ "Call   │ "Go to  │ "Read a │
│ grocer- │ home-   │  mom"   │  gym"   │ chapter"│
│  ies"   │  work"  │         │         │         │
└─────────┴─────────┴─────────┴─────────┴─────────┘

Enter fullscreen mode Exit fullscreen mode

One variable. Five values. Organized, indexed, and easy to work with.


Why Do We Need Arrays?

Let's compare the two approaches directly:

Without Arrays — A Variable for Each Value

let fruit1 = "Apple";
let fruit2 = "Mango";
let fruit3 = "Banana";
let fruit4 = "Grapes";
let fruit5 = "Orange";

console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
console.log(fruit4);
console.log(fruit5);

Enter fullscreen mode Exit fullscreen mode

Five variables. Five console.log calls. And if you want to add a sixth fruit? Create another variable, add another log. It doesn't scale.

With an Array — One Variable, All Values

let fruits = ["Apple", "Mango", "Banana", "Grapes", "Orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Enter fullscreen mode Exit fullscreen mode

One variable. One loop. Add 50 more fruits and the loop still works without changing a single line. That's the power of arrays.


How to Create an Array

Creating an array in JavaScript is simple. You use square brackets [] and separate the values with commas.

Syntax

let arrayName = [value1, value2, value3, ...];

Enter fullscreen mode Exit fullscreen mode

Examples

// Array of strings
let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

// Array of numbers
let marks = [85, 92, 78, 95, 88];

// Array of booleans
let answers = [true, false, true, true, false];

// Mixed array (JavaScript allows this — but use it sparingly)
let mixed = ["Pratham", 22, true, null];

// Empty array (you'll fill it later)
let todoList = [];

Enter fullscreen mode Exit fullscreen mode

JavaScript arrays are flexible — they can hold any data type, and you can even mix types in a single array. That said, in real-world code, you'll almost always keep arrays to one type for consistency and readability.


Accessing Elements Using Index

Every item in an array has a position called its index. And here's the thing that trips up every single beginner:

Array indexing starts at 0, not 1.

The first element is at index 0, the second at index 1, and so on.

Visual: How Indexing Works

Array:   ["Delhi", "Mumbai", "Bangalore", "Gurugram"]
Index:       0         1          2            3

Enter fullscreen mode Exit fullscreen mode

Accessing Elements

let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

console.log(cities[0]); // "Delhi"      — first element
console.log(cities[1]); // "Mumbai"     — second element
console.log(cities[2]); // "Bangalore"  — third element
console.log(cities[3]); // "Gurugram"   — fourth (last) element

Enter fullscreen mode Exit fullscreen mode

What Happens If You Use an Invalid Index?

console.log(cities[10]); // undefined — no error, just undefined
console.log(cities[-1]); // undefined — negative indexes don't work like Python

Enter fullscreen mode Exit fullscreen mode

JavaScript won't throw an error. It'll just quietly return undefined. Keep this in mind — it can cause silent bugs if you're not careful.

Accessing the Last Element

A common pattern you'll use all the time:

let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

let lastCity = cities[cities.length - 1];
console.log(lastCity); // "Gurugram"

Enter fullscreen mode Exit fullscreen mode

Why cities.length - 1? Because if there are 4 elements, the last index is 3 (remember, we start at 0). So length - 1 always gives you the last index.


Updating Elements

Changing a value in an array is as simple as assigning a new value to a specific index.

let fruits = ["Apple", "Mango", "Banana", "Grapes"];
console.log(fruits); // ["Apple", "Mango", "Banana", "Grapes"]

// Let's say I changed my mind about Banana
fruits[2] = "Strawberry";
console.log(fruits); // ["Apple", "Mango", "Strawberry", "Grapes"]

Enter fullscreen mode Exit fullscreen mode

You just point to the index and overwrite the value. The array updates in place — you don't need to create a new one.

A Practical Example

let scores = [70, 85, 60, 90, 75];

// Student at index 2 retook the exam and improved
scores[2] = 82;

console.log(scores); // [70, 85, 82, 90, 75]

Enter fullscreen mode Exit fullscreen mode

Adding to the End (Quick Preview)

You can also add new elements beyond the current length:

let colors = ["Red", "Blue"];

colors[2] = "Green"; // Adding at index 2
console.log(colors); // ["Red", "Blue", "Green"]

Enter fullscreen mode Exit fullscreen mode

But be careful — if you skip an index:

let colors = ["Red", "Blue"];

colors[5] = "Green"; // Skipping indexes 2, 3, 4
console.log(colors); // ["Red", "Blue", empty × 3, "Green"]
console.log(colors.length); // 6 — includes the empty slots!

Enter fullscreen mode Exit fullscreen mode

This creates "holes" in your array with empty slots. Don't do this intentionally — it leads to unexpected behavior.


The length Property

Every array has a built-in length property that tells you how many elements it contains.

let movies = ["Inception", "Interstellar", "The Dark Knight", "Tenet"];

console.log(movies.length); // 4

Enter fullscreen mode Exit fullscreen mode

Why Is length Useful?

You'll use it constantly:

  • Finding the last element: array[array.length - 1]
  • Looping through arrays: as the upper bound for your loop
  • Checking if an array is empty: array.length === 0
let tasks = [];

if (tasks.length === 0) {
  console.log("No tasks! You're free. 🎉");
}
// Output: "No tasks! You're free. 🎉"

Enter fullscreen mode Exit fullscreen mode

Important: length Is Not the Last Index

This is a subtle but important distinction:

Array:   ["A", "B", "C", "D"]
Indexes:   0    1    2    3
Length:  4

Last index = length - 1 = 3 ✅
Last index ≠ length = 4 ❌ (this would be out of bounds)

Enter fullscreen mode Exit fullscreen mode

I've seen this cause off-by-one errors more times than I can count. Remember: last index = length minus 1.


Looping Over Arrays

This is where arrays start to shine. The ability to process every element with a loop is what makes arrays so powerful.

1. The Classic for Loop

The most fundamental way to iterate through an array:

let fruits = ["Apple", "Mango", "Banana", "Grapes", "Orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(i + ": " + fruits[i]);
}
// 0: Apple
// 1: Mango
// 2: Banana
// 3: Grapes
// 4: Orange

Enter fullscreen mode Exit fullscreen mode

Let me break this down:

  • let i = 0 — start at the first index
  • i < fruits.length — keep going as long as i is less than the total count
  • i++ — move to the next index after each iteration
  • fruits[i] — access the element at the current index

2. The for...of Loop (Cleaner Syntax)

If you don't need the index and just want the values, for...of is cleaner:

let fruits = ["Apple", "Mango", "Banana", "Grapes", "Orange"];

for (let fruit of fruits) {
  console.log(fruit);
}
// Apple
// Mango
// Banana
// Grapes
// Orange

Enter fullscreen mode Exit fullscreen mode

No index tracking, no length check — just the values, one at a time. I use this whenever I don't need to know which position the element is at.

3. The while Loop (Less Common for Arrays)

You can use a while loop too, though it's less common for simple iteration:

let fruits = ["Apple", "Mango", "Banana", "Grapes", "Orange"];
let i = 0;

while (i < fruits.length) {
  console.log(fruits[i]);
  i++;
}

Enter fullscreen mode Exit fullscreen mode

Same result, just a different way to structure the loop. I'd stick with for or for...of for arrays — they're more readable and less prone to accidentally creating infinite loops.

When to Use Which Loop

Loop When to Use
for When you need the index or want full control
for...of When you just want the values — cleanest syntax
while When the stopping condition isn't index-based

Memory-Style Block Diagram

Here's how you can think about an array stored in memory — each block has an index and a value:

Variable: fruits
    │
    ▼
┌────────────────────────────────────────────────────────────┐
│                     Array in Memory                        │
├──────────┬──────────┬──────────┬──────────┬────────────────┤
│ [0]      │ [1]      │ [2]      │ [3]      │ [4]           │
│ "Apple"  │ "Mango"  │ "Banana" │ "Grapes" │ "Orange"      │
├──────────┴──────────┴──────────┴──────────┴────────────────┤
│ length: 5                                                  │
└────────────────────────────────────────────────────────────┘

Accessing: fruits[2]  →  goes to block [2]  →  returns "Banana"
Updating:  fruits[3] = "Kiwi"  →  block [3] changes from "Grapes" to "Kiwi"

Enter fullscreen mode Exit fullscreen mode

The key insight: array elements are stored contiguously (next to each other) and accessed by index — which makes looking up any element fast regardless of the array size.


Let's Practice: Hands-On Assignment

Part 1: Create an Array of 5 Favorite Movies

let movies = [
  "Inception",
  "Interstellar",
  "The Dark Knight",
  "Dangal",
  "3 Idiots"
];

console.log(movies);
// ["Inception", "Interstellar", "The Dark Knight", "Dangal", "3 Idiots"]

Enter fullscreen mode Exit fullscreen mode

Part 2: Print the First and Last Element

console.log("First movie:", movies[0]);
// First movie: Inception

console.log("Last movie:", movies[movies.length - 1]);
// Last movie: 3 Idiots

Enter fullscreen mode Exit fullscreen mode

Part 3: Change One Value and Print the Updated Array

// I changed my mind — replacing "Dangal" with "Oppenheimer"
movies[3] = "Oppenheimer";

console.log("Updated array:", movies);
// Updated array: ["Inception", "Interstellar", "The Dark Knight", "Oppenheimer", "3 Idiots"]

Enter fullscreen mode Exit fullscreen mode

Part 4: Loop Through the Array and Print All Elements

console.log("--- My Favorite Movies ---");

for (let i = 0; i < movies.length; i++) {
  console.log((i + 1) + ". " + movies[i]);
}
// 1. Inception
// 2. Interstellar
// 3. The Dark Knight
// 4. Oppenheimer
// 5. 3 Idiots

Enter fullscreen mode Exit fullscreen mode

Or with a for...of loop:

console.log("--- Movie List ---");

for (let movie of movies) {
  console.log("🎬 " + movie);
}
// 🎬 Inception
// 🎬 Interstellar
// 🎬 The Dark Knight
// 🎬 Oppenheimer
// 🎬 3 Idiots

Enter fullscreen mode Exit fullscreen mode


Key Takeaways

  1. Arrays are ordered collections of values stored in a single variable. They solve the problem of managing multiple related values without creating separate variables for each.
  2. Indexing starts at 0. The first element is array[0], not array[1]. The last element is always array[array.length - 1].
  3. Updating is simple — just assign a new value to a specific index: array[index] = newValue.
  4. The length property tells you how many elements the array contains. It's not the same as the last index (length - 1 is).
  5. Loops are how you process every element in an array. Use for when you need the index, for...of when you just want the values.

Wrapping Up

Arrays are probably the single most important data structure you'll work with in JavaScript. Every real project I've seen — from e-commerce product lists to social media feeds to to-do apps — uses arrays under the hood. Getting comfortable with creating, accessing, updating, and looping through them is foundational to everything that comes next: array methods, objects, APIs, and beyond.

I'm working through all of this in the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and I have to say — arrays were the first topic where I started feeling like I could actually build things, not just learn theory.

If this helped you, feel free to connect with me on LinkedIn or check out PrathamDEV.in. I'll keep writing as I keep learning — next up, array methods and objects.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode