JavaScript Array Length Mutation Explained

JavaScript Interview Question 🔥 const arr = [1, 2, 3, 4, 5]; arr.length = 2; console.log(arr); arr.length = 5; console.log(arr); Output: [1, 2] [1, 2, <3 empty items>] Why? Reducing length truncates the array. Increasing length adds empty slots, not undefined values. 👉 Interview Tip: Changing array.length directly mutates the array. #javascript #frontend #interview #coding #js #webdevlopement #365daysofjs #array

First time I saw this scenario...thanks man 🤗😶🌫️

While the behavior of manually setting an array's length is a fascinating JavaScript quirk, it is generally considered a bad practice in enterprise-level applications. Direct mutation of the length property can lead to side effects and unpredictable data states that compromise code maintainability. These kind of quirks might get you entry level jobs but not useful in application development

Because Javascript store reference of the array so whatever we do with arr will directly mutates original array

Like
Reply

Feeling glad to find this post as I was recently asked this same question and I passed it Yogesh Sharrma.

See more comments

To view or add a comment, sign in

Explore content categories