How are objects in JavaScript stored in memory?

In the official JSON documentation

An object is an unordered set of name / value pairs. An object begins with {(left curly brace) and ends with} (right curly brace). Each name followed by: (colon), and name / value pairs are separated, (comma).

Note I am new to Javascript and the JSON name itself (Javascript), I assume that the objects in Javascript are the same as JSON. Please correct me if I am wrong.

From the above definition, it seems that Javascript objects are most likely implemented using either a hash map, or with a BST, or with some similar data structure.

But when I insert key value pairs into the Node shell, they are inserted sequentially. This is what I tried in node shell

> var a = {} undefined > a['k1'] = 'a1' 'a1' > a['k3'] = 'a3' 'a3' > a['k2'] = 'a2' 'a2' > a['k4'] = 'a4' 'a4' > a['k5'] = 'a5' 'a5' > a { k1: 'a1', k3: 'a3', k2: 'a2', k4: 'a4', k5: 'a5' } 

Now, when printing a pairs of key values ​​are returned in the same order as the inserts. So my questions are:

  • Get a quick key search? I mean complexity O (log (n)) or better.
  • If JSON does not use a data structure such as BST, hashmap, or some similar DS, then how exactly do JSON objects lie in memory?

Update So, what about Javascript objects. Can someone comment on the basic implementation of Javascript objects.

+6
source share
1 answer

You are misleading JSON , which is a text- only serialization format that provides simple data exchange and simple javascript objects that are unordered property lists.

As MDN says:

An object is a set of properties, and a property is an association between a name and a value. The value of a property can be a function, which is then known as an object method.

Properties of objects can be considered as hash maps because they are not ordered. But this is often a little more complicated: when objects are based on a prototype, properties not found on the object look up the prototypes on which it is based.

With javascript objects, you get a guaranteed quick search, as this is an integral part of the implementation. But the implementation is not determined by the norm, and each engine can have its own.

+6
source

All Articles