What’s the Difference?

JavaScript Objects

JavaScript objects are composite data structures comprised of properties. You create an object and add properties to the object. For example:

Creating an object:

var obj = {};  or  var obj = new Object();

Adding an object:

obj.firstName = Chris;  or obj[firstName] = Chris;

The result:

var obj = {firstName: Chris,}

Javascript Object Creation with Constructor Functions

You can also create an object using a constructor function. Constructor functions are helpful when you want to create multiple objects quickly.

Lets say we had a PERSON object,:

var person = {firstName: Chris, lastName: Savage,age: 100,}

If you wanted to create multiple people objects you could use a constructor function:

Function Person (first, last, age) { this.firstName = first, this.lastName = last, this.age = age,};

You could create new objects using the new operator like so:

var chris = new Person(Chris, Savage, 100);
var anotherPerson = new Person(Jimmy, Smith, 45)

Using the constructor function is way faster than using the literal method (top method), when you need to create multiple instances of the same object.

Ruby Hashes vs JavaScript

Ruby hashes are basically the same as JavaScript Objects. You would create a Ruby hash by using:

person = {} or person = Hash.new

The big difference is that you add values to hashes by using the bracket method only, whereas in JavaScript you can use the dot notation or the bracket method (dot notation is the default, with exceptions).

In Ruby you would do the following:

person[:first_name] = Chris
person[:last_name] = Savage

With the result being:

person = { :first_name => Chris, :last_name=> Savage}

You would access the values in each key in the hash by:

puts Person[:first_name]
=> Chris

In JavaScript you would usually do:

person.firstName = Chris
person.lastName = Savage

With the result being:

person = { firstName: Chris, lastName: Savage}

You would access the value in each JS property (instead of calling it a key) by:

console.log(person.firstName)
=> Chris"

//or

console.log(person[“firstName”])
=> “Chris"

As you can see JavaScript objects and Ruby hashes are very similar.