DEV Community

Cover image for CRUD Operation with Array in JavaScript
Hidayt Rahman
Hidayt Rahman

Posted on

2

CRUD Operation with Array in JavaScript

Create

Create an array. It will contain programming languages.

const programmingLanguages = ["JavaScript", "Python"];
Enter fullscreen mode Exit fullscreen mode

Read

We have a lot of options to read it.

Print the entire array in a referenced way.

console.log(programmingLanguges); // (2) ["JavaScript", "Python"]
Enter fullscreen mode Exit fullscreen mode

Print the first item by using index

console.log(programmingLanguages[0]); // JavaScript
Enter fullscreen mode Exit fullscreen mode

Print all items by using for loop

for(var i = 0; i<programmingLanguages.length; i++) {
    console.log(programmingLanguages[i]);
    // JavaScript
    // Python
}
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

Add New

Let’s add a new language to the array using push().

programmingLanguages.push("Java");
// ["JavaScript", "Python", "Java"]
Enter fullscreen mode Exit fullscreen mode

Update

Let’s update java with C# using splice()

programmingLanguages.splice(2, 1, "C#")
// (3) ["JavaScript", "Python", "C#"]
Enter fullscreen mode Exit fullscreen mode

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

splice

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"]
Enter fullscreen mode Exit fullscreen mode

${HappyCode}

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more