36
CRUD Operation with Array in JavaScript
Create an array. It will contain programming languages.
const programmingLanguages = ["JavaScript", "Python"];
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
loopfor(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
Cleaner way to print all items.
forEach()
Cleaner way to print all items.
programmingLanguages.forEach((item, index) => {
console.log(`${index}. ${item}`);
// 0. JavaScript
// 1. Python
});
Let’s add a new language to the array using push().
programmingLanguages.push("Java");
// ["JavaScript", "Python", "Java"]
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
Let’s delete the C# from the language array.
We will use
We will use
splice()
again but this time we will pass only 2 parameters.programmingLanguages.splice(2, 1);
// (2) ["JavaScript", "Python"]
${HappyCode}
36