My smiling face

Paul Dynowski

Fledgeling Web Developer, All-Around Swell Guy

Facebook Twitter GitHub LinkedIn Email

JavaScript Objects vs. Ruby Hashes

One of these things is...well, quite a bit like the other, actually

Nov 12, 2015

What's an object in JavaScript, and how does it work?

An object, in JavaScript, is an unordered list of data stored as a series of name-value pairs. The name can technically be either a string or a number, but it is generally best to avoid using numbers as a name. Values can be...well, strings, numbers, or other objects. Look at a sample:

var video_game = {
  title: "Crusader Kings II",
  genre: "Grand Strategy",
  publisher: "Paradox Interactive"
}
This is the object literal method for creating objects - probably the most common way that you will create them.

Hey, wait a minute...that looks an awful lot like...

Yup. That, my friends, looks pretty much just like the implicit form for creating a symbol-based Hash in Ruby. Really, the only difference is that Ruby doesn't need the "var" declaration; other than that, it looks precisely the same.

Are there any differences, then?

Of course there are. Coding wouldn't be fun without the wondrous variety of language, now would it? Some of the differences are:

So, in summary...

Objects in JavaScript are quite a lot like hashes in Ruby, and can be used as such, if you'd like. However, they're really much more flexible than that, with the ability to be expanded into something that much more closely resembles a Ruby class.