Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
Landon Kuhn Avatar asked Jul 17 '09 14:07

Landon Kuhn


People also ask

Is a hash an object?

A hash object is dynamically created in memory at run-time. The size of a hash object grows as items are added and it contracts as items are removed. A hash object consists of key columns, data columns, and methods such as DECLARE, FIND, etc. A hash object's scope is limited to the DATA step in which it is created.

Is an object a hash map?

The key in a hashmap can be any datatype, this includes arrays and objects. Meanwhile, objects can only use integers, strings, and symbols as their keys. Hashmaps are organized as linked lists, so the order of its elements is maintained, which allows the hashmap to be iterable.

Can an object be a key?

Yes, we can use any object as key in a Map in java but we need to override the equals() and hashCode() methods of that object class.

Which one is a difference between an array and a hash?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.


2 Answers

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

like image 80
Marcin Avatar answered Sep 21 '22 05:09

Marcin


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 
like image 26
Ian Elliott Avatar answered Sep 22 '22 05:09

Ian Elliott