Object Literals and benefits in java scripts

JavaScript, by default does not come with built-in namespace or class but as it's extremely a flexible language you can create namespace in JavaScript by object literals. Based on wikipedia definition "literal is a notation for representing a fixed value in source code."  you can simply create Object literal by using: 

  1. A colon which separates the property name from value.
  2. A comma which separates each name and value pair from the next.


For example:

  1. var myInfo = {
  2.     Name: "Ehsan",
  3.     Age: 25,
  4.     Job: "Developer"
  5. };

You can also define nested object literal like this:

var myInfo = {

  1. Info1:{
  2.     Name: "Ehsan",
  3.     Age: 25,
  4.     Job: "Developer" 
  5.     }, 
  6. Info2:{
  7.     Website:"ehsanghanbari.com",
  8.     Mail:"mails@ehsanghanbari.com"
  9.     }
  10. };

Object literals makes for good code organization, means of encapsulating data, enclosing it in a tidy package to minimize the use of global variables which can cause problems when combining code. Imagine if you wanted to write all of the code above in your functions, it would be something like stars war!

By using object literal there is no need to invoke constructors directly or maintain the correct order of arguments passed to functions and unobtrusive event handling.

Rather than static values, object literal could contain kinds of value, such as attribute, array or function:

  1. Var obj={
  2.         Title: "a good title",
  3.         Books: ["JavaScript", "Domain Driven Design"],
  4.         order:  function() {console.log("blah blah");
  5.            }
  6. }


In comparison to constructor, constructors need to be executed so it will be slower. But object literals need to be parsed (defined) in loading the script.

Note: When you define object as literal, you build the object by code; so  if you use this keyword it will no meaning because it's not exist yet.

Tags: JavaScript

comments powered by Disqus