2

I am learning javascript. In one of the document, I read we can modify the length of array. I tried as below and it worked.

var array = new Array(1, 2, 3, 4 ,5);
array.length = 4;

Now array becomes [1, 2, 3, 4].

But the same is not working on Strings.

var str = new String("abcdef");
str.length = 5;

str is not getting modified. Is there any specific reason to not allow this behavior on strings?

kadina
  • 5,042
  • 4
  • 42
  • 83

5 Answers5

3

Strings are immutable by design. You can't change them, but you can reassign the reference to a new string value. If you want to shorten a string, you can use the String slice() method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

drone6502
  • 433
  • 2
  • 7
3

String are immutable. For a new length of the string, you need an assignment wich copies the string with a new length.

var string = 'abcdef';

string = string.slice(0, 4);

console.log(string);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

.length property is used differently for string, because they are immutable: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

If you want to alter the length of a string you can create a new string using slice.

Josh Adams
  • 2,113
  • 2
  • 13
  • 25
1

When you log your String object in the console, you can see why this is not working:

var str = new String("abcdef");
str.length = 5;
console.log(str)

Thus, you cannot set the length property here. We are talking about the "immutability" of strings in JavaScript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • Doesn't answer the question. Instead, this is illustrating how to observe the results. The question was on why. – Mikejg101 Mar 19 '18 at 16:12
0

Attempting to assign a value to a string's .length property has no observable effect.

MDN Link

var myString = "bluebells";

// Attempting to assign a value to a string's .length property has no observable effect. 
myString.length = 4;
console.log(myString);
/* "bluebells" */
Muhammet Can TONBUL
  • 3,217
  • 3
  • 25
  • 37
  • 1
    In addition to the great quick answers below, you can read a nice explanation about immutable objects here: https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript – Josh Adams Mar 19 '18 at 15:21
  • Thanks for the link @JoshAdams – kadina Mar 19 '18 at 15:23