Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Object Literal in in JavaScript

An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces. In this tutorial let us learn how to create objects using object Literal with examples. Learn how to use the Object Property Initializer Shorthand syntax etc.

Creating objects using object literal Syntax

The following is an example of creating a new JavaScript object using object literal syntax.

  1. Enclose everything in a curly bracket
  2. Use colon as a separator between a property name (key) and its value
  3. Use a comma as a separator between each key-value pair
  4. Comma at the end of the last key-value pair is ok.
        
var person = { 
    firstName: "Allie",      //FirstName Property
    lastName: "Grater",      //lastName Property
    age: 50                  //age
}; 

                
        
    

Object Literal Syntax Examples

Spaces and line breaks are not important. You can use multiple lines or combine all of them into a single line

        
let person = {firstName: "Allie",lastName: "Grater",age: 50};
 

                
        
    

Trailing commas are ok. Note the comma after age:50,

        
let person = {firstName: "Allie",lastName: "Grater",age: 50,};
 

                
        
    

An object with no properties

        
let empty = {};

                
        
    

Object with two numeric properties.

        
let point = { x: 0, y: 0 };
 

                
        
    

More complex values

        
let point = { x: 10, y: 20 };
 
let p2 = { x: point.x, y: point.y + 1 };
 

                
        
    

These property names can include space. For example 'main title'. You need to use the string inside a quote

        
let book = {
  "main title": "Head first Javascript",
}
 
 

                
        
    

You can also make use of a hyphen

        
let book = {
  "main-title": "Javascript Tutorial",
}
                
        
    

The property names can also include reserved words like for and let. The rules of the identifier do not apply to property names.

        
let obj = {
  for: "for is reserved keyword",
  let: "let is also reserved keyword"
};
 
                
        
    

The properties can have any value including the objects, functions, etc. The following book object consists of a property author , which is an object.

        
let book = {
  "main title": "Eloquent JavaScript",
   author: {
    firstName: "Marijn",
    lastName: "Haverbeke"
  }
};
 
 
                
        
    

In the following example, getAuthorName is a function

        
let book = {
    "main title": "Eloquent JavaScript",
    author: {
        firstName: "Marijn",
        lastName: "Haverbeke"
    },
    getAuthorName: function () { return this.author.firstName + ' ' + this.author.lastName }
 
};
 
console.log(book.getAuthorName())
 
                
        
    

Property Names

An JavaScript allows us to use any string as Property Names. The Strings may include spaces or special characters or even reserved keywords like let. If the name does not confirm the JavaScript identifiers rules, then you need to enclose it in quotes while declaring it.

        
let book = {
    "Author Name": 'Marijn Haverbeke',
    "Book@Title": "Eloquent JavaScript",
    let:"This is reserved keyword"
};
 
 
console.log(book)
 
                
        
    

If you use any other types as property names, then they are converted to a string. For example in the following example, we use numbers as property names, JavaScript converts them to strings, when creating the properties.

        
        
values = {
  1: "One",
  2: "two",
  3: "three",
};
 
console.log(values);
 
 
//This is same as above
values = {
  "1": "One",
  "2": "two",
  "3": "three",
};
 
                
        
    
        
var person = { 
  firstName: "Allie",      //FirstName Property
  lastName: "Grater",      //lastName Property
  age: 50,                  //age
  getName : function () {
     console.log(this.firstName + ' ' + this.lastName)
  }
};
 
person.getName();    //Allie Grater  
        
    

object literal vs new Object()

There is no difference between them.

Whenever we create a new object via an object literal, JavaScript invokes the new Object() to create the object. i.e. objects created from object literal inherit properties from Object.prototype.

        
var person = { 
  firstName: "Allie",   
  lastName: "Grater",   
  age: 50               
};
 
console.log(person)
                
        
    

The above example does the same thing as the following example.

        
var person = new Object()
person.firstName="Allie"
person.lastName="Grater"
person.age = 50
 
console.log(person)
                
        
    

Creating Multiple Objects

Use a function, if you wish to create multiple objects using the same recipe. The following example creates two Person objects.

        
function person(firstName, lastName, age) {
 
    return { 
        firstName: firstName, 
        lastName: lastName, 
        age: age
    }
}
 
 
let allie=person("Allie","Grater",50)
let Paul=person("Paul","Molive",25)
 
console.log(allie)
console.log(Paul)
    
        
    

Object Property Initializer Shorthand

In the above example, property names match the variable name. In such cases, you can use the variable name directly. This syntax was introduced in ES6.

        
function person(firstName, lastName, age) {
 
    return { 
        firstName,      //Shorthand
        lastName, 
        age
    }
}
 
let allie=person("Allie","Grater",50)
let Paul=person("Paul","Molive",25)
 
console.log(allie)
console.log(Paul)
    
        
    

When you use the variable name directly, the JavaScript will look for the similarly named variable in the scope chain. If it finds one, it will create a property with that name and assigns the value of the variable to it.

                            
let middleName="Test"
 
function person(firstName, lastName, age) {
 
  return { 
      firstName,      //Shorthand
      lastName, 
      middleName,     //middleName comes from the global variable
      age
  }
}
 
let allie=person("Allie","Grater",50)
console.log(allie)
 
  
    
        
    

Another example

                            
let firstName = "Allie"
let lastName = "Grater"
 
let person = {
   firstName,
   lastName
};
 
 
console.log(person)  //{firstName: "Allie", lastName: "Grater"}
 
  
    
        
    

You can mix and match both approaches

                            
function person(firstName, lastName, age) {
 
    return { 
        firstName,      //Shorthand Assignment
        lastName, 
        age,
        active:true     //Regular 
 
    }
}
 
  
    
        
    

Property Initializer Shorthand for functions

Similarly, you can define a function without using the function keyword or a colon. Check out the add & get methods in the following example. This option was introduced in ES6

                            
var products = {
 
  items:[] ,
 
  add(item) {
    this.items.push(item);
  },
  
  get(index) {
    return this.items[index];
  },
 
};
 
function item(code, name) {
 
  return   {
    code,
    name
  }
 
}
 
products.add(item('1',"Desktop PC"));
products.add(item('2',"Laptop"));
products.add(item('3',"Printer"));
 
console.log(products.get(0));     //{code: "1", name: "Desktop PC"}
 
  
    
        
    

Getters & Setters

The following example shows how to create Property getters and setters using the object Literal example

                            
let obj = {
  get value() {
    return this._value;
  },
  set value(val) {
    this._value = val;
  }
};
 
 
console.log(obj.value)      //undefined
 
obj.value = 10
console.log(obj.value)      //10
 
  
    
        
    

Computed Property Name

You can also use an expression, which results in a single value to be used as Property Name. We need to enclose the expression inside square brackets( [])

In the following example, we create a Author Name property in book object

        
let author = 'Author Name';
 
 
let book = {
    [author]: 'Marijn Haverbeke',
    "Book Title": "Eloquent JavaScript"
};
 
 
console.log(book[author]); // Marijn Haverbeke
console.log(book['Author Name']); // Marijn Haverbeke
 
console.log(book["Book Title"]); // Eloquent JavaScript
 
 
    
        
    

From ES6 onwards, you can use the computed property name as a part of the object literal syntax. For Example, we placed the expression directly inside the square brackets( [])

        
let prefix = "Book";
 
let book = {
    [ prefix + "Author"]: 'Marijn Haverbeke',
    [ prefix + "Title"]: "Eloquent JavaScript"
};
 
console.log(book[prefix + "Author"]); // Marijn Haverbeke
console.log(book["BookAuthor"]);      // Marijn Haverbeke
 
//We can also use this. because there is no space in the property name
console.log(book.BookAuthor);        // Marijn Haverbeke
 
    
        
    

You can also invoke a function inside square brackets.

        
let prefix = "Book";
 
let book = {
    [ getAuthorName()]: 'Marijn Haverbeke',
    [ prefix + "Title"]: "Eloquent JavaScript"
};
 
function getAuthorName() {
  return prefix+'Author'
}
 
    
        
    

The following example uses the fullNameFieldName() function to assign the property name to a function.

        
function fullNameFieldName() {
  return "full name";
}
 
var person = {
  firstName: "Allie",
  lastName: "Grater",
  [fullNameFieldName()]: function () {
    return this.firstName + " " + this.lastName;
  },
};
 
console.log(person["full name"]()); //Allie Grater
console.log(person[fullNameFieldName()]()); //Allie Grater
 
    
        
    

Object Literals as Lookups

You can use the objects as lookups. The following code shows how to get values from Object properties.

The following example shows you how to create a class in JavaScript. We can then use the new keyword to objects from the class.

                        
function getMonthName (monthNo) {
    var names = {
      "1": "January",
      "2": "February",
      "3": "March",
      "4": "April",
      "5": "May",
      "6": "June",
      "7": "July",
      "8": "August",
      "9": "September",
      "10": "October",
      "11": "November",
      "12": "December",
    };
    return names[monthNo] || "Invalid";
  }
  
  var monthName = getMonthName(1);
  console.log(monthName);    //January
 
  monthName = getMonthName(13);  
  console.log(monthName);   //Invalid