Back to blog

Resize or Clear an Array Using Length πŸ’»

Hey, guys! How's it going? Today we're going to talk about how to efficiently resize or clear an array using the JavaScript length property.

Sometimes we need to adjust the size of an array to fit new values or remove old ones. And the best way to do this is through the Array.length property.

Resizing an Array

To resize an array, you can simply set the length property to the new size you want. If the new size is smaller than the current size, the extra values will be removed. If it's larger, the array will be filled with empty values.

const myArray = [1, 2, 3, 4, 5];console.log(myArray);// [1, 2, 3, 4, 5]myArray.length = 3;console.log(myArray);// [1, 2, 3]

In the example above, we set the length of the myArray array to 3, and the extra values were removed. Simple, right?

Clearing an Array

To clear an array, simply set its length to 0.

const myArray = [1, 2, 3, 4, 5];console.log(myArray);// [1, 2, 3, 4, 5]myArray.length = 0;console.log(myArray);// []

In the example above, we set the length of the myArray array to 0, removing all its values.

Conclusion

As we've seen, length is a very useful property for efficiently resizing or clearing an array. It's a simple and easy-to-use solution that can save a lot of time and effort.

So, have you used length to clear or resize an array before? Share your experience with me in the Instagram! If you have any questions, don't hesitate to ask.

Let’s go! πŸ¦…


Previous post Next post

Comments (0)

This article has no comments yet 😒. Be the first! πŸš€πŸ¦…

Add comments