Ehsan Ghanbari

Experience, DotNet, Solutions

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:

var myInfo = {
    Name: "Ehsan",
    Age: 25,
    Job: "Developer"


You can also define the nested object literal like this:


var myInfo = {

    Name: "Ehsan",
    Age: 25,
    Job: "Developer" 
    Mail:"[email protected]"


Object literals make 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:


Var obj={
        Title: "a good title",
        Books: ["JavaScript", "Domain Driven Design"],
        order:  function() {console.log("blah blah");


In comparison to the 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 an object as literal, you build the object by code; so if you use this keyword it will no meaning because it does not exist yet.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus