D Dev Notebook

JavaScript Array

JS

In JavaScript, an Array is used to store multiple values in a single variable. You can think of it as a list or collection of items.

Creating an Array:

// Array of numbers
let numbers = [1, 2, 3, 4, 5];

// Array of strings
let fruits = ["Apple", "Banana", "Cherry"];

Accessing Array Elements:

Array elements have index numbers starting at 0:

let fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits[0]);  // Apple
console.log(fruits[1]);  // Banana
console.log(fruits[2]);  // Cherry

Adding Elements:

Use methods like push() and unshift():

let fruits = ["Apple", "Banana"];

fruits.push("Cherry"); // Adds to the end
console.log(fruits); // ["Apple", "Banana", "Cherry"]

fruits.unshift("Mango"); // Adds to the start
console.log(fruits); // ["Mango", "Apple", "Banana", "Cherry"]

Removing Elements:

Use methods like pop() and shift():

let fruits = ["Apple", "Banana", "Cherry"];

fruits.pop(); // Removes last element
console.log(fruits); // ["Apple", "Banana"]

fruits.shift(); // Removes first element
console.log(fruits); // ["Banana"]

Looping Through an Array:

Using a loop to display all items:

let fruits = ["Apple", "Banana", "Cherry"];

for(let i = 0; i < fruits.length; i++){
    console.log(fruits[i]);
}
//output 
Apple
Banana
Cherry

Using Array Methods:

  1. forEach() (Iterates through elements):
fruits.forEach(function(item) {
    console.log(item);
});
  1. map() (Transforms each element into a new array):
let numbers = [1, 2, 3];
let squares = numbers.map(function(num) {
    return num * num;
});

console.log(squares); // [1, 4, 9]
  1. filter() (Creates new array based on condition):
let numbers = [10, 15, 20, 25];
let filtered = numbers.filter(function(num) {
    return num > 15;
});

console.log(filtered); // [20, 25]

Array of Objects:

Arrays can store objects, which is useful for real-world data:

let users = [
    {name: "Alice", age: 25},
    {name: "Bob", age: 30},
    {name: "Carol", age: 28}
];

// Accessing object's property in array:
console.log(users[1].name); // Bob

Benefits:

  • Store multiple items efficiently.
  • Easy to access, add, and remove items.
  • Great for looping and handling lists of data.
  • Provide many built-in powerful methods (map, filter, reduce, etc.).

Array Projects

To-Do List Application

Features:

  • Add new tasks to the list
  • Remove tasks by clicking a delete button
  • Mark tasks as completed by clicking on them
  • Shows clear usage of JavaScript arrays, DOM manipulation, and event handling.

Project Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Interactive To-Do List</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #eef2f5;
      padding: 20px;
      display: flex;
      justify-content: center;
    }

    .container {
      width: 400px;
      background-color: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }

    h2 {
      text-align: center;
    }

    input[type="text"] {
      width: 75%;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    button {
      padding: 10px 15px;
      border: none;
      background-color: #2196F3;
      color: white;
      border-radius: 4px;
      cursor: pointer;
    }

    ul {
      list-style-type: none;
      padding: 0;
      margin-top: 20px;
    }

    li {
      padding: 10px;
      margin-bottom: 10px;
      background-color: #f9f9f9;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
    }

    .completed {
      text-decoration: line-through;
      color: #888;
    }

    .delete-btn {
      background-color: #f44336;
      border: none;
      color: white;
      padding: 5px;
      border-radius: 3px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <div class="container">
    <h2>Interactive To-Do List</h2>
    <input type="text" id="taskInput" placeholder="Enter new task">
    <button onclick="addTask()">Add Task</button>

    <ul id="taskList"></ul>
  </div>

  <script>
    let tasks = [];

    function addTask() {
      const taskInput = document.getElementById('taskInput');
      if (taskInput.value.trim() === '') return;

      tasks.push({
        text: taskInput.value,
        completed: false
      });

      taskInput.value = '';
      displayTasks();
    }

    function displayTasks() {
      const taskList = document.getElementById('taskList');
      taskList.innerHTML = '';

      tasks.forEach((task, index) => {
        const li = document.createElement('li');
        li.textContent = task.text;

        if (task.completed) li.classList.add('completed');

        li.addEventListener('click', () => {
          task.completed = !task.completed;
          displayTasks();
        });

        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = 'Delete';
        deleteBtn.classList.add('delete-btn');

        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation(); // Prevents triggering li click event
          tasks.splice(index, 1);
          displayTasks();
        });

        li.appendChild(deleteBtn);
        taskList.appendChild(li);
      });
    }

    displayTasks(); // Initially display tasks (empty)

  </script>

</body>
</html>

On this page