Enumerable Blog
About coding, web development, and fun to be had in tech

Simple JavaScript Objects

Last Updated:

As a Ruby developer, I was surprised to find out how simple JavaScript objects can be and I decided to write up this summary of my revelations.

Revelation #1: JavaScript Objects Are Like Ruby Hashes

JavaScript objects are dictionaries, or associative arrays (just like a Ruby Hash). JavaScript objects can contain properties with associated values (like words and their definitions in the dictionary) that may be accessed to retrieve the value. When the value of a property is a function, we call it a method.

Try these examples in your browser's JavaScript console: ⌥⌘J in Chrome (Mac), other browsers.

Download This Code Block

// The most basic object in JavaScript is {} var basic_object = {}; console.log(basic_object instanceof Object); // => true // An object with properties var obj = { foo: 'bar', nothing: null }; console.log(obj.foo); // => 'bar' console.log(obj.nothing); // => null console.log(obj.missing); // => undefined // Set new properties obj.num = 5; console.log(obj.num); // => 5

Revelation #2: Functions and Arrays are Objects Too!

Some of the built-in JavaScript objects inherit from Object.

Download This Code Block

// Functions are Objects var fn = function() {}; console.log(fn instanceof Function); // => true console.log(fn instanceof Object); // => true // You can add properties to a function but this is // rarely done in practice: fn.foo = 'bar'; console.log(fn.foo); // => 'bar' // Arrays are Objects Too! var ar = []; console.log(ar instanceof Array); // => true console.log(ar instanceof Object); // => true ar.category = 'supercool';

Additional built-in objects which inherit from Object are Date, RegExp, and Error.

Revelation #3: Get a Copy of a Function - Afterall it's Just an Object

In Ruby, there is rarely any difference between a function call with or without parentheses. In Javascript, however, if you don't include parentheses after a function, you get the function object back. This allows you to grab copies of functions and use them elsewhere:

Download This Code Block

var Logger; var greeter, tayZonday, zombieKid; // A constructor that returns a function object function Logger(message) { // set function to a variable var logger = function() { console.log(message); }; // return the logger. Don't use parentheses to // return the function object rather than the // result of the function return logger; } // Each Logger returns a custom function! greeter = new Logger('hello world'); tayZonday = new Logger('Chocolate Rain'); zombieKid = new Logger('I like turtles'); greeter(); // => 'hello world' tayZonday(); // => 'Chocolate Rain' zombieKid(); // => 'I like turtles'

In the example above, a simpler solution is to return the function definition directly rather than setting the logger variable. I did not do that here for the sake of example.

comments powered by Disqus