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.


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