kadina
kadina

Reputation: 5376

why we can't modify string length in javascript where as we can modify the length of array?

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?

Upvotes: 2

Views: 691

Answers (5)

messerbill
messerbill

Reputation: 5629

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

Upvotes: 1

Muhammet Can TONBUL
Muhammet Can TONBUL

Reputation: 3538

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" */

Upvotes: 0

Josh Adams
Josh Adams

Reputation: 2099

.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.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386624

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);

Upvotes: 3

drone6502
drone6502

Reputation: 433

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

Upvotes: 3

Related Questions