Create JavaScript Object using Object Literal Example

Using object literals is the simplest way to create an object in Javascript. An object literal also called an object initializer, is a comma-separated set of paired names and values.

Create JavaScript Object using Object Literal Example

Let's create a Javascript object using an object literal:
// using Object Literals
var user = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : 'ramesh@gmail.com',
    age : 29,
    getFullName : function (){
        return user.firstName + " " + user.lastName;
    }
}

console.log(JSON.stringify(user));
console.log(user.getFullName());

// access object properties
console.log('firstName :',  user.firstName);
console.log('lastName :',  user.lastName);
console.log('emailId :',  user.emailId);
console.log('age :',  user.age);
Output:
{"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}
Ramesh Fadatare
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29

Comments