CRUD Operation with Array in JavaScript

Create
Create an array. It will contain programming languages.
const programmingLanguages = ["JavaScript", "Python"];
Read
We have a lot of options to read it.
Print the entire array in a referenced way.
console.log(programmingLanguges); // (2) ["JavaScript", "Python"]
Print the first item by using index
console.log(programmingLanguages[0]); // JavaScript
Print all items by using for loop
for(var i = 0; i<programmingLanguages.length; i++) {
    console.log(programmingLanguages[i]);
    // JavaScript
    // Python
}

The above snippet will print all items of the array individually.

Print all items by using forEach()
Cleaner way to print all items.
programmingLanguages.forEach((item, index) => {
     console.log(`${index}. ${item}`);
     // 0. JavaScript
     // 1. Python
});
Add New
Let’s add a new language to the array using push().
programmingLanguages.push("Java");
// ["JavaScript", "Python", "Java"]
Update
Let’s update java with C# using splice()
programmingLanguages.splice(2, 1, "C#")
// (3) ["JavaScript", "Python", "C#"]

splice() is used to add, update or delete an item from the array.

  • The first parameter selects the item by index
  • 2nd parameter selects the number of items
  • 3rd parameter add a new item of the selected item
Delete
Let’s delete the C# from the language array.
We will use splice() again but this time we will pass only 2 parameters.
programmingLanguages.splice(2, 1);
// (2) ["JavaScript", "Python"]

${HappyCode}

36

This website collects cookies to deliver better user experience

CRUD Operation with Array in JavaScript