w3resource

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:


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that empties an array by setting its length property to zero while preserving the original reference.
  • Write a JavaScript function that returns a new empty array without modifying the original array.
  • Write a JavaScript function that uses a loop to remove elements one by one using pop().
  • Write a JavaScript function that clears an array and confirms that subsequent operations are performed on an empty array.

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.