📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
There are various ways to empty an Array in JavaScript.
The easiest one is to set its length to 0:
let strArray = ["A", "B", "C","D", "E"]; strArray.length = 0;
Another method mutates the original array reference, assigning an empty array to the original variable:
var intArray = [1,2,3,4,5,6,7] intArray = [];
Complete Example
var strArray = ["A", "B", "C","D", "E"]; var intArray = [1,2,3,4,5,6,7] function emptyArray(){ console.log(" Before empty an array : " + strArray); strArray.length = 0; console.log(" After empty an array : " + strArray); console.log(" Before empty an array : " + intArray); intArray = []; console.log(" After empty an array : " + intArray); } emptyArray();
Output:
Before empty an array : A,B,C,D,E After empty an array : Before empty an array : 1,2,3,4,5,6,7 After empty an array :
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:
Comments
Post a Comment
Leave Comment