66

In JavaScript, what is the difference between an object and a hash? How do you create one vs the other, and why would you care? Is there a difference between the following code examples?

var kid = {
 name: "juni",
 age: 1
}

And:

var kid = new Object();
kid.name = "juni";
kid.age = 1;

And:

var kid = new Object();
kid["name"] = "juni";
kid["age"] = 1;

Can you think of any other code example I should illustrate?

The core question here is what is the difference between an object and a hash?

Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
  • 2
    I think your statement "difference between and object and a hash" is meant to mean "difference between and object and a (hash)map". – Peter Jul 17 '09 at 14:11
  • good point... but isn't Hash an actual Javascript type? – Landon Kuhn Jul 17 '09 at 14:12
  • 8
    There is no such thing as a hash type in JavaScript. `{}` is just a short-hand initializer for the `Object` type. And `[]` is just a short-hand initializer for the `Array` type. – Blixt Jul 17 '09 at 14:13
  • There is a `Hash` type in MooTools, which might be what you have seen. – Blixt Jul 17 '09 at 14:13
  • 1
    Perhaps it is the Prototype Hash class that has me confused: http://www.prototypejs.org/api/hash – Landon Kuhn Jul 17 '09 at 14:15
  • Ah, I see that one has it as well. Yes, that would be where you got `Hash` from. See this page for types available in core JavaScript: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference – Blixt Jul 17 '09 at 14:18
  • 1
    If you are only looking to store key/value pairs, there is absolutely no need for that 'Hash' type in Prototype. – SolutionYogi Jul 17 '09 at 14:53
  • @landon9720 - re: **other code example** - the three original examples are all `anonymous Object`. You could also declare a `class Kid` that would look much like your second example. but depending on how you check whether `var kid` is an `Object` you might get a different answer. See: http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript – Jesse Chisholm May 07 '15 at 22:05

11 Answers11

63

There just isn't any. All three of those are literally equal.

Marcin
  • 7,874
  • 7
  • 45
  • 49
  • 4
    And yet ... over here http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript they show that various `isObject` implementations _could_ give different answers. – Jesse Chisholm May 07 '15 at 22:02
19

They are different notation systems that you can use interchangeably. There are many situations where using the bracket syntax [ ] can be more appealing, an example would be when referencing an object with a variable.

var temp  = "kid";
var obj = new Object();
obj[temp] = 5; // this is legal, and is equivalent to object.kid
obj.temp = 5; // this references literally, object.temp
Ian Elliott
  • 7,588
  • 5
  • 35
  • 42
6

In other languages such as Java and C# it's possible to use any object (not just a string or a number) as a key in a hash table/hash map, which is not the case in JavaScript: keys are simply converted to strings.

var h = {}, k = {};
h[k] = "One";
alert( h[ "[object Object]" ] ); // Alerts "One"

It can be useful to use arbitrary objects as keys, in which case you can use something like jshashtable.

Disclaimer: I wrote jshashtable.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
5

Actually, every object in JavaScript IS a hash. This is a hash of object's properties and methods. In fact, everything in Javascript is a hash (i.e a list of name/value pairs).

Every time you call object's method, property, or just reference any variable, you perform internal hash lookup.

Thevs
  • 3,189
  • 2
  • 20
  • 32
  • To be concise, it's a generalized map instead of a hash that every object in JavaScript is. In languages like Java, C#, and etc., maps are used for homogeneous type of data, while in JavaScript, the data for the ``map`` is just heterogeneous. – lcn Sep 25 '13 at 16:55
4

There isn't any difference in any of your samples. They are all objects with named properties. You've just shown different ways of creating/referencing those properties.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
3

They are the same.

you can use them interchangeably.

Jimmy Chandra
  • 6,472
  • 4
  • 26
  • 38
3

I think this is all the same. The third version could used with dynamic property names. The first one is the shortest to write.

TheHippo
  • 61,720
  • 15
  • 75
  • 100
2

They are the same. Just as [] and new Array() are the same.

For more information on the core types of JavaScript, have a look at the MDC Core JavaScript 1.5 reference.

If you want proof that {} is the same as new Object():

Object.prototype.helloWorld = function () { alert('Foo!'); };
var a = new Object();
var b = {};
a.helloWorld();
b.helloWorld();

!!! WARNING ACHTUNG AVERTISSEMENT !!! Never, ever assign to the prototype property of the Object type in production code. You'll be polluting the whole global namespace.

Blixt
  • 49,547
  • 13
  • 120
  • 153
1

Technically, they are the same. When you write code, you can easily do myobject['someproprty' + 'somethingElseConcatenated], which you cannot do when using the "dot notation" - myobject.someproperty is all you can do.

Douglas Crockford, one of autors of ECMAscript, suggests not to use var a = new Object() syntax for some reason I didn't quite catch. Anyway, it's worth watching his presentation if you're interested in it (it consists of several parts, the first one is here http://video.yahoo.com/watch/111593/1710507)

naivists
  • 32,681
  • 5
  • 61
  • 85
1

Every engine(browser) implements it differently but let focus on chrome's V8(based on performance tests I performed a year ago on most of the modern browsers they give similar performance boosts if you follow v8 guidlines).

What it basically happens is:

  1. To implement a dynamic object on which properties can be added and deleted on the fly - a hashtable is the simplest solution - but speedwise its not as efficient as a regular object in java(random access...).
  2. What V8 does is trying to guess based on few strategies if your object is a regular object(has final set of properties set in specific order, etc...) or a hashtable. At first it assumes this is a simple object and each new property causes creation of a new structure of an object and copying of the old one on it plus the new property. If the object is categorize as "difficult" - it is moved to a hushtable.
  3. If v8 notices too many "mistakes" - it moves everything to hashtables - therefore you get poor performance (thats why you want to use constructors that init all of your members or structures inited in a json...)

Please see this links: https://developers.google.com/v8/design#prop_access

www.quora.com/Are-JavaScript-Objects-implemented-as-HashTables-Is-key-value-access-O-1

jayconrod.com/posts/52/a-tour-of-v8-object-representation

Also a very good lecture: https://www.youtube.com/watch?v=UJPdhx5zTaw

Hope it helps...

Max Leizerovich
  • 1,536
  • 1
  • 10
  • 7
0

Actually, there is nothing called 'hashtable' or 'hashmap' in JavaScript. The object in JavaScript behaves like a 'hash' [objects in JavaScript are simply key/value properties] and hence the confusion.

SolutionYogi
  • 31,807
  • 12
  • 70
  • 78