Truncate Arrays with JavaScript's Length Property

A method easier than "methods"? 🤯 I was recently working on a problem where I needed to trim an array. I started writing a standard for loop to shift elements and was ready to reach for splice()... but then I tried an experiment. I simply wrote: arr.length = arr.length - 1 It worked perfectly. No methods, no complicated logic, just a direct property change. I actually thought I had found a bug! But after checking the MDN documentation, I realized this is a well-known, intentional feature of JavaScript. Why this is easier than splice() or pop(): Zero Complexity: You don't need to remember arguments or return values. Instant Truncation: If you want to keep only the first 3 items, just set .length = 3. Done. Performance: It's a high-speed way to discard elements without the overhead of method calls. Do you think you'll start using this as your default way to shorten arrays now, or will you stick to splice for better code readability? comment below .. #javascript #codingtips #frontend #react #webdevelopment #programming #webdev #softwareengineering Nikhil Kilivayil Brototype

  • text

Well done Vijay! Keep diving into the fundamentals of JS.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories