Skip to content
Related Articles

Related Articles

Improve Article

How to truncate an array in JavaScript ?

  • Last Updated : 23 Feb, 2021
Geek Week

In JavaScript, there are two ways of truncating an array. One of them is using length property and the other one is using splice() method. In this article we will see, how we can truncate an array in JavaScript using both these methods.

  1. length Property
  2. splice() Method

Using array.length property: Using array.length property, you can alter the length of the array. It helps you to decide the length up to which you want the array elements to appear in the output.

Syntax:

// n = number of elements you want to print
var_name.length = n;

In the above syntax, you can assign the size to the array using array.length property according to the required output.

Example:



Javascript




<script>
  const num = [1, 2, 3, 4, 5, 6];
  num.length = 3;
  console.log( num );
</script>

Output:

[1, 2, 3]

As you can see in the above output, only three elements get printed. Assigning a value to the array.length property truncates the array and only the first n values exists after the program.

Using splice() Method: The splice() method removes items from an array, and returns the removed items.

Syntax:

// n=number of elements you want to print
var_name.splice(n); 

Example:

Javascript




<script>
  const num = [1, 2, 3, 4, 5, 6];
  num.splice(4);
  console.log(num);
</script>

Output:

[1, 2, 3, 4]

The above are the 2 ways using which you can truncate an array in JavaScript.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!

My Personal Notes arrow_drop_up
Recommended Articles
Page :