Explicitly creating a Wrapper object

What I understood about the wrapper object is this: if we declare a primitive type and access some properties, then the wrapper object is created internally, and as soon as the operation is done, it is discarded, for example.

var str1="Stack"


The third line will give me 5 because the second line is being executed on the temporary object and the third line will create a new temporary object.

But if I create my own wrapper object explicitly, eg.

var str1=new String("Stack")


Then also why I am getting 5. Here I have no dependency on an internal temporary wrapper object that is discarded when the opertaion finishes. Here I dedicate to the wrapper object, then why can't I assign a length value, and if we can't set the length, then why does Javascript allow me to set the length? Can anyone clarify this.


source to share

1 answer

As per the javascript spec line length is unchanged. Therefore your code "str1.length = value" does nothing.

String creation through the constructor --- var str1 = new String ("Stack") --- or through normal creation --- var str1 = "Stack" --- creates different types of objects. But since their prototype is the same ( proto : String), the length remains the same.


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

This property is not changed after the String object is initialized. It has attributes {[[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false}.

See below for example code:

var str1 = "Stack"
var str2 = new String("Stack")
str1 === str2
typeof str1
typeof str2
String {0: "S", 1: "t", 2: "a", 3: "c", 4: "k"
, length: 5
, [[PrimitiveValue]]: "Stack"}0: "S"1: "t"2: "a"3: "c"4: "k" length: 5
__proto__: String
[[PrimitiveValue]]: "Stack"




All Articles