Making Your JavaScript Code Easier to Understand: Object Literals

JavaScript

JavaScript LogoWhen it comes to organizing your object literals, there are multiple approaches you can take

Object Literals are a very useful feature of JavaScript. They allow you to easily build structures of data or functionality (or both mixed together), without too much fuss and drama. The syntax is simple and they make it easy to name-space your code. But, when your object literals start to grow in size, they can become a bit difficult to manage. And, it can sometimes make your code harder to follow.

In the next few examples, I will cover a couple of  alternate ways to organize your JavaScript Object Literals. This can make your code easier to manage and understand.
Example # 1

In Example # 1, we have an object literal that has been assigned to the variable “mathFuncs”. This object has three members: “add”, “subtract” and “multiply”. Each is a function. This is not too bad, but what if each function was tens or even hundreds of lines of code? The entire “mathFuncs” object itself would grow to become thousands of lines long. This can become unwieldy. Also, if while making edits, one semicolon gets knocked out of place, the entire object is likely to become defective, which will pretty much kill the script.

Example # 2

In Example # 2, “mathFuncs” is initially one line of code: an empty object. We then extend the object by adding more properties. In this case, the three properties we add are “add”, “subtract” and “multiply”. Functionally, there is no difference between this approach and Example # 2. These anonymous functions will perform no differently. What is different is that the code is a little bit easier to follow. First you see that “mathFuncs” is an empty object, and then we add properties to it. These properties are all functions, so they should be referred to as “methods”. Also, if you have a bug in one of the anonymous functions, it is less likely to break the entire script, and could be easier to track down.

Since these functions are very small, there is yet another level of optimization that we can apply:

Example # 3

In Example # 3 we tightened up the first three functions because there is so little going on in them, so it’s no harm to make them all one line each. Again, it’s just easier for someone else to quickly read and understand. We added two new properties, both anonymous functions as well. Since these are bigger functions (let’s pretend they are each 50+ lines of code), we put them last so that they are a bit out of the way, and we only have to see all that implementation code if we care to.

This is all a matter of preference. From time to time, I think that not everyone realizes that there are options when it comes to object literals and how you choose to write them out. The approach taken in Example # 1 is fine, especially when the objects are small. But when you have many properties in your object, and those properties are anonymous functions that contain tens or hundreds of lines of code, it can make your logic hard for someone else to follow.

Summary

There are many ways to skin a cat, and as many ways to organize your JavaScript code. The purpose of this post was to offer a few suggestions that can make your object literals a little bit easier to read, especially for someone else who, in the future, might have to read, understand and then make changes to your code.

JavaScript Closures – The Absolute Basics: Getters and Setters

JavaScript

JavaScript LogoThe next step in mastering JavaScript closures is being able to “get” or “set” a private variable.

In Part I of this series: JavaScript Closures – The Absolute Basics, I discussed wrapping one function with another, which produces a closure. When that returned function is assigned to a variable, as long as that variable is alive, it (a function) has access to the context of the function that wraps it. This means that the outer (or “wrapping”) function can contain a private member, but the wrapped function has access to it. In that post, the example code consisted of a function that returned the private member.

Let’s take this one step further: we want to be able to “get” and “set” that private member in real time. Consider the following code:

Example # 1

Here is the JsFiddle link: http://jsfiddle.net/a6LBf/

In Example # 1, we first create a global variable named “drink” that is set equal to “wine”. Our reason for doing this will become apparent in a moment. Next, we have a variable named “foo”, which is set equal to an anonymous function. Here is where the “closure” stuff comes in: That anonymous function (i.e. “foo”) returns an object literal. That object literal contains two properties: “getDrink” and “seDrink”. Both are anonymous functions.

After the declaration of the anonymous function “foo”, we create a variable named “bar” that is equal to the return value of “foo” (i.e. we execute “foo”, and set the variable “bar” equal to that). Because “foo” returns an object literal, it is almost as if we simply did this:

But that does not completely represent what is going on here. Although “bar” is, in fact, equal to an object literal that has two anonymous functions as members, that object literal was returned by a function (and that is a critical detail). Because that object literal was returned by a function, the two anonymous functions that are members of the object literal have access to the function that returned them. Because they will execute in the context of “foo”, they have access to the private scope of “foo”.

Ok, so what does this all mean?

Remember when we created a global variable named “drink”, and set it equal to “wine”? Well, in Example # 1, when we say: “console.log( drink )”, and the output is “wine”, that is because in the global context, “drink” equals “wine”. But there is another variable named “drink” in play. That variable is in the private scope of “foo” and it is set equal to “beer”.

Hang in there, we are getting to the good stuff now…

In Example # 1, when we say: “console.log( bar.getDrink() )” and the output is “beer”, that is because “getDrink()” has access to the private scope of “foo”, and in the private scope of “foo”, “drink” is equal to “beer”. Next, when we say: “console.log( bar.setDrink(“juice”) )”, we are mutating (i.e. changing) the value of the variable “drink” that exists in the private context of “foo”. This is because:

  • “bar” was set equal to the value of whatever “foo” returned
  • “foo” returned an object literal
  • The object literal that “foo” returned contains a member: “setDrink()”
  • “setDrink()” has access to the variable “drink” which is in the private scope of “foo”
  • We change that private variable “drink” to “juice” using “bar.setDrink()”

If you run the jsfiddle link for Example # 1, you will see this all in action (make sure you have your JavaScript console open). Once the code has run, type the following in your JavaScript console: “console.log( bar.getDrink() )” the return value will be “juice”.

Summary

There is no such thing as a wasted moment when it comes to understanding closures in JavaScript. This is a powerful feature of the language. In this post, we discussed getting and setting the value of a variable that exists in the private scope of a function that returned an object literal. Stay tuned for more to come on this topic which does, at times, seem complex, but is more than worth the effort, and is an important tool in your JavaScript belt.

How to Create a JavaScript Object Literal

JavaScript

JavaScript LogoLearn how to quickly and easily create your first Object Literal, and give it properties and methods

There seems to be a bit of mystery surrounding the subject of JavaScript Object Literals. It is actually a simple concept and it’s easy to get started. There is a great deal of depth to the subject, but creating your first JavaScript Object Literal does not need to be complicated.

The simplest way to create an object literal is to assign an empty object to a variable. For example: var foo = {}; That is it. In that one line, you have created an object literal.

Now, that object is empty. Objects have two kinds of “things”: properties and methods. A property can be any valid JavaScript type (i.e. string, number, boolean, function, array, etc.). A method is essentially a property of the object to which you have assigned an anonymous function. So the property is now equal to a function. It is still a property of the object, but because it “does” something, we now call it a “method”.

Example # 1

Here is the JSFiddle Link for Example # 1: http://jsfiddle.net/jzrDw/

In Example # 1, we create a new Object Literal by assigning an empty object to the variable “foo”. Next, we give foo a property named “drink” and assign a value of “beer” to it. In this case the value of “drink” is a string (“beer”), but it could easily have been a number (i.e. foo.drink = 5) or a boolean (foo.drink = true) or any valid JavaScript type.

Example # 2

In Example # 2, we have added a second property to foo. This property, “say” has an anonymous function assigned to it, so now we call it a “method”. That method: foo.say does not do too much; it just outputs “hello world!” to the console. But nonetheless, it is a method of foo.

Here is the JSFiddle Link for Example # 2: http://jsfiddle.net/PWHM5/

Here is an important note: In the first two examples, technically, we created an object literal by assigning an empty object to the variable “foo”. Then we added a property and a method using dot notation (i.e. foo.property = value). But true “Object Literal” syntax involves creating the object properties as you create the object.

Example # 3

In Example # 3, we use Object Literal Notation. In the end, we have the same result as the previous example, but we achieve it using true Object Literal Notation. The difference is that in the previous example, we created an empty object, and then added properties to it. In Example # 3, we created those properties as we created the object itself.

Here is the JSFiddle Link for Example # 3: http://jsfiddle.net/sGY7E/

Summary

There is plenty more to talk about here. For example, there is the subject of “context” in Object Literals. But this post is about getting started, and to show that creating a JavaScript Object Literal is no mystery. What you do with that object is up to you. But you can be sure that objects in JavaScript are important features of the language, as they allow you to write more powerful and expressive code.

A Video Tutorial About JavaScript Object Literals

Helpful Links for JavaScript Object Literals

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

http://blog.kevinchisholm.com/javascript/difference-between-object-literal-and-instance-object/

http://www.dyn-web.com/tutorials/obj_lit.php

What is the difference between an Object Literal and an Instance Object in JavaScript ?

JavaScript

JavaScript LogoAlthough a JavaScript object literal and a JavaScript instance object are both objects, they differ in their inherent nature and features


Object Literals

An object literal is “flat”. You create it, you add properties and methods to it, and all of those properties and methods are public. You can mutate any members of that object at any time. A JavaScript object literal does not, by nature, provide private scope. But any of the members of an object literal can certainly be a function that is capable of private scope. Object literals are useful because they allow you to create clean name-spaced code that is easy to pass around and consume.

Example # 1

In example # 1, we have defined a JavaScript object literal and assigned it to the variable “data”. This object has two members: the property “fname” and the method “addOne”. At run time, we can mutate this object very easily and add new properties (e.g. “lname”) and methods (i.e. “say”). The upside is that this object is totally exposed and we can access or mutate any of its members any time we like, with no problem. (Remember that if an object member is a function, then that function does provide its own private scope.) The downside of this object is that it does not inherently have a private scope. It also doesn’t have the kind of initialization that is provided by a constructor upon creation.

The output for example # 1 is:

foo
5
bar
baz
this is the say function

Instance Objects

An instance object is what is returned when instantiating a JavaScript constructor function, using the JavaScript “new” keyword. When you say “var bar = new Foo()”, “bar” becomes an “instance” of the function “Foo()”. Any expressions within Foo() are executed, any local variables in Foo() are copied and provided in “bar”, and the value of “this” inside of “bar”, refers to “bar”. The function “Foo” is never changed in any way; it simply acts as a “blueprint” for “bar”, and “bar” is an “instance” of “Foo”. Any local variables inside of “bar” are completely private and can only be muted by privileged members of that object.

Example # 2

In example # 2, we have created a constructor function. A JavaScript constructor function is a function that is not meant to be executed directly. For example, we never plan to do the following: “Foo()”. Instead, a constructor is meant to be instantiated. This means that you create an “instance” of that function using the JavaScript “new” keyword. We have created an instance of Foo() by saying “var bar = new Foo()”. So, now we have a variable named “bar” that is an exact copy of Foo().

What makes “bar” differ from our JavaScript Object Literal that we defined in Example # 1, is that when our instance object (“bar”) is created, any execution code in the constructor (i.e. “Foo()” ) runs. In addition, any private variables defined in the constructor remain private in the instance object (i.e. “_color”).

What makes this scenario a little more special than that of the object literal is that we can have privileged methods. These are methods that are made public by the use of the “this” prefix, but they have access to the instance object’s private members (i.e. “_color”). So, when we run this code, the constructor function code runs (“welcome to your new instance object”). We attempt to output the value of “_color”, but “undefined” is returned, because “_color” is private and cannot be accessed outside of “bar”. We then use the privileged method “getColor()” to get the value of _color the correct way, and “blue” is returned. We then change the value of “_color” using the privileged memer “setColor()”, and return its value using “getColor()” again (“red”).

Summary

Both Object Literals and Instance Objects have their place and purpose in JavaScript. The power of Object Literals is in their lightweight syntax, ease of use, and the facility with which they allow you to create name-spaced code. Instance Objects are powerful because they are derived from a function, they provide private scope when they are created, and expressions can be executed on instantiation.

Helpful links for JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.javascriptkit.com/javatutors/oopjs.shtml

http://www.dyn-web.com/tutorials/obj_lit.php

http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance

The JavaScript “for…in” Statement – Don’t Leave Home Without It

JavaScript

JavaScript LogoObjects in JavaScript are first class types that have become a critical component to modern front-end web development. The “for…in” statement allows you to fully examine any object at run-time<

Making objects, instantiating objects, and enjoying all the wonderful properties and methods that we baked into our objects is what advanced JavaScript is all about these days. Let’s face it… it’s hard to imagine a useful JavaScript-based application that does not, in some way, implement object oriented technology. The “for…in” statement is one of the most essential tools in our belt when it comes to introspection in JavaScript.

“Introspection” in JavaScript is the act of “looking into” an object, to discover what it has inside. The answer is: “properties and methods.” But, the thing is, you don’t always know the name of the object that you will want to “look into” or exactly when you will have to do it. Also, as we know, an object member can itself be an object, which has properties and methods, and one or more of those properties might be another object with its own properties and methods… or a method might return an object, that has properties and methods…. and so on.

So, add this all up and what you get is the need to “look into” an object without knowing anything about it. It may be an object that you did not create, so our introspection tool cannot look for a specific set of named members; it just has to be able to say:  “the object that you told me to look into contains the following properties and methods,” and based on the object that we fed to that tool, the answer can vary.

The JavaScript “for…in” loop is incredibly simple and equally powerful. With its basic syntax, we can easily say: “for each X in Y… do this…”. X is the object’s property and Y is the object. So, if I had an object named “foo”, I could say “for X in foo”. If foo had 5 properties, then the loop would run 5 times. In each iteration of the loop, “X” will represent the current property that is being “looked at”. To access the property name, simply refer to X (i.e. alert(x) ), and to access the property value, refer to object[x] (i.e. alert(foo[x]) ). The reason that we use the bracket notation, and not dot notation, is that dot notation requires a string literal (i.e. foo.name), whereas with bracket notation, we can place any valid expression inside the brackets, such as a variable (e.g. foo[X] ).

Now what follows this is the “loop”, which is a set of curly brackets. So, our syntax looks as follows:

Inside “the loop”, we can do whatever we like. Typical scenarios are to do something with either the property name (i.e. X) or the property value (i.e, foo[X]). Let’s look at an example of a JavaScript “for in” loop that does something.

Example # 1

The output for Example # 1 would be:

the value of color, is: blue
the value of name, is: fred
the value of say, is: function (){ return “this is the say function” }

In Example # 1, the object “foo” has three members: two properties and one method. So, the “loop” executes three times. In each case, we output the name of the member “prop” and the value of the member “foo[prop]”.

Hmmm… ok, but what if one of the members is a function? Can’t we do more than just output what the name of the function is?

Sure! Functions are meant to be executed, so let’s execute a function if we find one!

Example # 2

In Example # 2, we examine each property courtesy of the “typeof” operator. If the property currently being “looked at” is a function, we assign the value of the property (the actual function code) to a variable, and then execute that variable. The output of Exmple # 2 is:

the value of color, is: blue
the value of name, is: fred
we found a function, and here it comes: hello from is the say function

Summary

So, as you can see, the sky is pretty much the limit with regard to the JavaScript for…in statement. It’s a very powerful introspection tool, i.e., one that gives us the ability to examine the properties and methods that an object contains. The reason that this statement is so important is that you may not always know the name of the object that you want to “look into” or much about it at all. This means that the JavaScript for…in statement allows you to abstract away the details of the future object that you will want to examine, and just say: “whatever object I reference, find out what is inside that object and tell me all  about it!”

Helpful links for the JavaScript “for…in” statement

 http://www.w3schools.com/js/js_loop_for_in.asp

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://msdn.microsoft.com/en-us/library/55wb2d34(v=vs.94).aspx

How to Include a Function as a JavaScript Object Literal Member

JavaScript

JavaScript LogoJavaScript object literals can contain not only properties, but methods too

Some may automatically think of a JavaScript object as a name / value pair scheme with flat members that are essentially just scalar values. Fortunately, this is not quite the case. An object literal can also include functions among its members. Those functions can do everything that any function would otherwise do; it just happens to be a member of an object. You define a function as an object member simply by assigning an anonymous function to the key, instead of the usual scalar value.

Example # 1:

The output for Example # 1 would be: “Hi, my name is: Don Draper, my address is: 123 E. Maple Ave., and I am 36, years old” The reason for this is that in addition to the properties we have defined, we define a member that is a reference to an anonymous function. That function takes two arguments: the current year and the year Don was born. It calculates Don’s age, and then returns the result.

Some might say: “Why not just declare a function and use it?” You can certainly do that, but as I have covered in previous posts, it is usually best practice to create name-spaced objects in order to keep the global space clutter free. When doing so, you can define your members within your object. And, one or more of those members can be a function. I can think of few circumstances when this is not a good idea. It makes your code more readable and easy to manage.

Summary

There are many useful things you can do when making a function a member of an object literal. This post simply covers the basics.

Helpful Links about JavaScript Objects

http://www.w3schools.com/js/js_objects.asp

http://www.quirksmode.org/js/associative.html

http://www.javascriptkit.com/javatutors/oopjs.shtml