JavaScript: Empty an array keeping the original
JavaScript Array: Exercise-33 with Solution
Empty Array
Write a JavaScript script to empty an array while keeping the original.
Sample Solution:
JavaScript Code:
// Declare and initialize an array
var arr = [1, 3, 6, 3, -5];
// Output the contents of the array before modification
console.log(arr);
// Set the length of the array to 0, effectively clearing its contents
arr.length = 0;
// Output the contents of the array after modification
console.log(arr);
Sample Output:
[1,3,6,3,-5] []
ES6 Version:
// Declare and initialize an array
let arr = [1, 3, 6, 3, -5];
// Output the contents of the array before modification
console.log(arr);
// Set the length of the array to 0, effectively clearing its contents
arr.length = 0;
// Output the contents of the array after modification
console.log(arr);
Live Demo:
See the Pen JavaScript - Empty an array keeping the original - array-ex- 33 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to find an array contains a specific element.
Next: Write a JavaScript function to get nth largest element from an unsorted array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-array-exercise-33.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics