Difference between an object and a hash?

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?


Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

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.