"JavaScript Tip: The Power of Array.length"

💡 JavaScript Tip: The Magical length Property of Arrays 😎 Most developers know that array.length gives the number of elements… But do you know how powerful (and tricky) it actually is? Let’s explore 👇 --- 🔹 1. Length is not read-only const arr = [1, 2, 3, 4]; arr.length = 2; console.log(arr); // [1, 2] 👉 Setting length truncates the array! All elements beyond the new length are removed. --- 🔹 2. You can also extend the array const arr = [1, 2]; arr.length = 5; console.log(arr); // [1, 2, <3 empty items>] 👉 Empty slots are created (they’re not undefined, they’re missing). --- 🔹 3. Length doesn’t always mean “last index + 1” const arr = []; arr[5] = 42; console.log(arr.length); // 6 👉 Sparse arrays have holes — indexes 0 to 4 don’t exist, but length still counts the last index + 1. --- 🔹 4. Deleting items doesn’t reduce length const arr = [10, 20, 30]; delete arr[1]; console.log(arr.length); // 3 console.log(arr); // [10, <1 empty item>, 30] 👉 The hole remains — length ignores deletions! --- ⚡ Quick Recap: Operation Effect on length push() / unshift() Increases pop() / shift() Decreases delete arr[i] No change arr.length = n Trims or extends --- 💭 Takeaway: length is not just a property — it’s a controller of your array’s shape and size. Handle it carefully to avoid silent bugs! --- #JavaScript #WebDevelopment #Frontend #CodingTips #JSArrays

To view or add a comment, sign in

Explore content categories