How to use length Property In Javascript
Using Javascript 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
let_name.length = n;
Example: In this example, we will see the basic use of Javascript`s array.length property.
const num = [1, 2, 3, 4, 5, 6];
num.length = 3;
console.log(num);
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 exist after the program.
How to truncate an array in JavaScript ?
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 these methods.
These are the following ways to truncate an array:
Table of Content
- Using length Property
- Using splice() Method
- Using slice() Method
- Using Lodash _.truncate() Method
- Using Array.prototype.pop() in a loop
Contact Us