By Saheb Sutradhar - Updated On 12-03-2024
How to Empty an Array in JavaScript, along with practical examples.
Emptying an array means removing all its elements, leaving it devoid of any content. Here are several ways to Clear an Array in JavaScript
let myArray = [1, 2, 3, 4];
myArray = []; // Now myArray is an empty array
length
property of an array to 0, you effectively clear its contents.let anotherArray = ['a', 'b', 'c', 'd', 'e', 'f'];
anotherArray.length = 0; // Clears the array
splice()
Methodsplice()
method removes elements from an array.let yetAnotherArray = [10, 20, 30, 40];
yetAnotherArray.splice(0, yetAnotherArray.length); // Clears the array
pop
()
in a Looppop()
until its length becomes 0.
let arrayToClear = ['apple', 'banana', 'cherry'];
while (arrayToClear.length > 0) {
arrayToClear.pop();
}
Remember that the choice of method depends on your specific use case. Whether you want to create a new array or modify the existing one, these techniques provide flexibility for handling arrays in JavaScript.
Happy coding!
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024