Javascript Trivia V1
Mohan Murali
Posted on January 19, 2020
What is Array in Javascript?
Arrays are special data structure, which are used to store data in sequential order. Turns out, that array in javascript are nothing but plain objects with properties named as numbers instead of a proper name.
typeOf [];
"object"
We can even use the Object method on array to get the data.
var a = ['a', 'b', 'c'];
Object.keys(a);
["0", "1", "2"]
If we want we can define array as plain objects instead of using the array syntax.
var b = { 0:'a', 1:'b', 2:'c'};
b[1];
"b"
Square Bracket Selector
We can't access this property value using the dot operator (.) as its a number. So we have to use the square brackets ([]). The difference between accessing the property using dot operator and using square brackets is that when we use dot operator, the name after dot is literally the name of the property, whereas when using the square brackets, the expression between the brackets is evaluated to get the property name.
The following statements will produce the same results
b[1];
b[3-2];
const getNum = (a, b) => b-a;
b[getNum(5,6)];
Index as Properties
We can also check if the array has the index using the property validation functions like Object.hasOwnProperty or the 'in' method.
var a = ['a', 'b', 'c'];
1 in a;
true
Object.hasOwnProperty(a);
true
We can even delete the array index with the delete method (which remove the property value)
var a = ['a', 'b', 'c'];
delete a[1];
1 in a;
false;
Object.keys(a);
(2)["0", "2"];
Doing this will set the value of a[1] to undefined.
a[1];
undefined.
Credits
Most of the knowledge shared in this blog is from the book 'Eloquent Javascript' by Marijn Haverbeke with my own experimentations and thoughts included. I would recommend people to pick up this book as it has a lot more information than what I have shared.
Thanks
Posted on January 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.