Arrays and Wrapper Objects in JavaScript

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)

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: