~/
hackweb.dev
JavaScript Arrays Basics
Quiz
⌘K
...
~/
/tutorials
/js/js-arrays-basics/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/7js-arrays-basics
Write
Preview
Diff
# JavaScript Arrays Basics Arrays are ordered collections of values. They let you store multiple items in a single variable. ## Creating Arrays ```javascript let empty = []; let numbers = [1, 2, 3, 4, 5]; let fruits = ["apple", "banana", "orange"]; let mixed = [1, "hello", true, null]; ``` ## Accessing Elements Arrays use zero-based indexing: ```javascript let fruits = ["apple", "banana", "orange"]; fruits[0]; // "apple" (first element) fruits[1]; // "banana" fruits[2]; // "orange" fruits[3]; // undefined (out of bounds) ``` ## Array Length ```javascript let fruits = ["apple", "banana", "orange"]; fruits.length; // 3 // Get the last element fruits[fruits.length - 1]; // "orange" ``` ## Adding Elements ```javascript let fruits = ["apple", "banana"]; fruits.push("orange"); // Add to end // ["apple", "banana", "orange"] fruits.unshift("grape"); // Add to beginning // ["grape", "apple", "banana", "orange"] ``` **Tip:** `push` is faster than `unshift` because it doesn't reindex. ## Removing Elements ```javascript let fruits = ["apple", "banana", "orange"]; let last = fruits.pop(); // Remove from end // last = "orange" let first = fruits.shift(); // Remove from beginning // first = "apple" ``` ## Modifying Elements ```javascript let fruits = ["apple", "banana", "orange"]; fruits[0] = "grape"; // Change first element fruits[3] = "mango"; // Add to specific position ``` ## Complete Example: Todo List ```javascript let todos = []; function addTodo(text) { todos.push({ text, done: false }); } function completeTodo(index) { if (index >= 0 && index < todos.length) { todos[index].done = true; } } function listTodos() { todos.forEach((todo, i) => { let status = todo.done ? "✓" : "○"; console.log(`${i + 1}. ${status} ${todo.text}`); }); } addTodo("Learn JavaScript"); addTodo("Build a project"); listTodos(); completeTodo(0); listTodos(); ``` ## Best Practices 1. **Use descriptive names** — `fruits`, not `arr` 2. **Check bounds** — Don't access out-of-range indices 3. **Use `const` for arrays** — If you won't reassign the variable 4. **Handle empty arrays** — Check length first 5. **Use arrays for related data** — Group logically ## Common Mistakes 1. **Off-by-one errors** — Arrays start at 0 2. **Forgetting length** — Accessing undefined indices 3. **Mutating while iterating** — Can skip elements 4. **Confusing `push` and `unshift`** — Different performance 5. **Using `for...in` on arrays** — Use `for...of` instead
No changes yet
Reset to original
Submit suggestion
cancel