-1

In C if i declare

 int x[4]

Which tells me its an integer array with each array element size fixed of size 4.

So after initialization when I access x[3] : address of array +element size which is 2 * index => (x[3]=2000+2*3) Assuming 2000 is the array address

In Javascript

We have

var a=[3,"rohan",6] //Dynamically typed

Here array elements are not equally sized for eg.a[2] is a string whose element size is different than a[0] which is an integer

So how does the array access work?

  • To understand Arrays in JavaScript, you also need to understand that Objects in general are basically key-value pairs. An Array in JavaScript is no different, actually. The "numeric indexes" are intrinsically converted to strings. The value at a[0] and a["0"] are the same. – Greg Burghardt Jun 12 '18 at 11:54
2

In dynamic languages, all values are typically implemented as objects with a common base (or pointers to structures with a common header, where the header describes the type). The effect is that we can pass pointers to these values around, and all pointers have the same size. The array then contains pointers to the actual values.

E.g. an array object a = [3, "rohan", 6] might be implemented like this:

| a
v
+--------+---------+------+-----+
| header | storage | size | cap |
+--------+-|-------+------+-----+
           |
           v
           +---+---+---+
           |   |   |   | (this memory is the "C array")
           +-|-+-|-+-|-+
.------------'   |   |
v                |   v
+--------+---+   |   +--------+---+
| header | 3 |   |   | header | 6 |
+--------+---+   |   +--------+---+
                 v
                 +--------+------+---------+
                 | header | size | "rohan" |
                 +--------+------+---------+

Object layouts equivalent to this are also used by Perl, CPython, or OpenJDK (The Java equivalent would be something like Object[] a = { new Integer(3), "rohan", new Integer(6) };)

0

JS arrays are not like your primitive C arrays; they are Objects: A list of key,value pairs with some special syntax to make it look and behave like an Array.

  • Is this the same case for python? As python too has arrays that act like this – Mohan Pierce Jun 12 '18 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.