Arrays and Wrapper Objects in JavaScript
November 8, 2019 Leave a comment
Arrays
Every array in JS behind the scenes is an Object which means array element can be accessed with index as an integer and also as a string
myArr[0] is same as myArr["0"]
As arrays are objects, can we use DOT NOTATION here? No because the property name is a number which is invalid identifier
If array is an object then how does myArray[0] works? Its because JS does Type Coercion behind the scenes and converts number to string.
Since array indexes are just property names in an object, we can assign element to any index, say
myArr[100] = "xyz";
*** myArr.length -> gives 101 because its actually not the length of an array rather its equal to (max_index + 1)
var myArr = ["hello", "how", "are"];
console.log(myArr.length);
myArr[20] = "you";
console.log(myArr.length);
If you try to access a index which is not defined then you get value ‘undefined’ rather than ArrayIndexOutOfBoundsException like in Java
var myArr = [100, 200];
console.log(myArr[0] +';'+ myArr[1] +';'+ myArr[2]);
Note: Additional elements in array can be added dynamically
Wrapper Objects in JS
By default when we create a variables, they are created as primitives but when we use DOT NOTATION on primitive, JS converts primitive into its corresponding wrapper object and performs the DOT OPERATION and then discards the object.
var value = "Hello World";
value.length; // here value primitive is converted into wrapper string object and then performs length
typeof value; // shows "string" which is a primitive
Similar wrappers are available for Number, Boolean and also Symbol(in ES6)
Recent Comments