[go: up one dir, main page]

DEV Community

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

Posted on

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}

Top comments (0)