user2477345
user2477345

Reputation:

Redefining length property in string object

What is the difference between this two?

var me=[];
console.log(me.length)//outputs 0
me.length=5;
console.log(me.length)//outputs 5

but here,

var me = new String("Angus");
console.log(me.length = 2); //(error in strict mode)
console.log(me.length); //5 (not 2 )

I m being unable to assing the length property to string object why?I m not replacing the original length property but creating new one in the string object even though it will fail what is the reason here?Thank u

Upvotes: 2

Views: 383

Answers (4)

AllTooSir
AllTooSir

Reputation: 49372

Array:

In the first case , if you set the length of an array the the array gets padded with undefined . Look at the documentation. Read further

The value of the length property is an integer with a positive sign and a value less than 2 to the 32 power (232).

You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements does not increase; for example, if you set length to 3 when it is currently 2, the array still contains only 2 elements.

And the ECMA Script documentation:

The length property initially has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

String:

String's length property is read-only . The properties of a string value can not be changed. Look at the ECMA Script documentation:

The number of characters in the String value represented by this String object.

Once a String object is created, this property is unchanging. It has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

Upvotes: 1

Ted
Ted

Reputation: 3260

For the Array object in javascript, the length property is designed to be set and will truncate the array. So it is not read only. Somehow the String class seems to have set up the length property to be read only. If you want to shorten a string you can use the substring property:

var length = 2;
var myString = "Angus";
var myTruncatedString = myString.substring(0,length);

Upvotes: 0

CoursesWeb
CoursesWeb

Reputation: 4237

length returns the number of elements of an array, or the number of characters in string. It is only read-only, not writable.

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71918

Strings are immutable, you just can't change their length like that.

I m not replacing the original length property but creating new one in the string object even though it will fail

Why do you think that? You can't have two properties with the same name, so yes, you are trying to replace the original property.

If you want a substring, use:

me = me.substr(0,2);

Upvotes: 0

Related Questions