Array and Objects-working with data in javascript

What are Arrays?
In simple words, arrays are a continuous set of memory locations used to store data. Arrays can be accessed by pointing to the first location of the array (i.e., where it starts). They are used to store multiple values in a single variable and are especially useful when you want to work with lists or collections of data.
In some programming languages, arrays are considered primitive data types, while in others, they are non-primitive data types depending on how they're implemented.
What are Objects in JavaScript?
Objects are a fundamental data type in JavaScript that store data in the form of key-value pairs. For every key, a value is assigned, and that value can be of any data type — such as a number, string, boolean, function, array, or even another object.
javascriptCopyEditconst person = {
name: "John",
age: 30,
isStudent: false,
address: {
city: "New York",
zip: 10001
}
};
In the example above, the object person
contains various key-value pairs. It even includes a nested object under the address
key.
How is an Array Related to an Object?
In JavaScript, arrays are actually a special type of object. While typical objects use named keys (e.g., name
, age
), arrays use numeric indices (e.g., 0
, 1
, 2
) to access elements.
javascriptCopyEditconst fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // Outputs: banana
Under the hood, this array is represented as:
javascriptCopyEdit{
0: "apple",
1: "banana",
2: "cherry",
length: 3,
__proto__: Array.prototype
}
Just like objects, arrays in JavaScript have a hidden property called __proto__
, which points to the prototype of the array (Array.prototype
). This prototype contains built-in methods like push()
, pop()
, map()
, filter()
, and more.
Prototype vs. proto
prototype
: A property of functions (used as constructors) that defines properties and methods inherited by instances.__proto__
: A hidden property of every object that points to the prototype object it was derived from.
For example:
javascriptCopyEditfunction Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log("Hello, " + this.name);
};
const john = new Person("John");
john.greet(); // Hello, John
Here, Person.prototype
defines the method greet
, and the object john
has access to it via john.__proto__
.
Conclusion
Arrays and objects are both essential parts of JavaScript.
Arrays are specialized objects with numeric keys and built-in methods.
Both rely on the concept of prototypes for inheritance and shared functionality.
Understanding how arrays and objects work helps you write more powerful and flexible JavaScript code.
Subscribe to my newsletter
Read articles from Sanjay p directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
