w3resource

JavaScript: Empty an array keeping the original

JavaScript Array: Exercise-33 with Solution

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.



Follow us on Facebook and Twitter for latest update.