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.
The following is an example of creating a new JavaScript object using object literal syntax.
var person = {
firstName: "Allie", //FirstName Property
lastName: "Grater", //lastName Property
age: 50 //age
};
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())
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
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)
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)
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
}
}
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"}
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
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
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