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.
Table of Contents
Creating objects using object literal Syntax
The following is an example of creating a new JavaScript object using object literal syntax.
- Enclose everything in a curly bracket
- Use colon as a separator between a property name (key) and its value
- Use a comma as a separator between each key-value pair
- Comma at the end of the last key-value pair is ok.
1 2 3 4 5 6 7 8 | 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
1 2 3 | let person = {firstName: "Allie",lastName: "Grater",age: 50}; |
Trailing commas are ok. Note the comma after age:50,
1 2 3 | let person = {firstName: "Allie",lastName: "Grater",age: 50,}; |
An object with no properties
1 2 3 | let empty = {}; |
Object with two numeric properties.
1 2 3 | let point = { x: 0, y: 0 }; |
More complex values
1 2 3 4 5 | 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.
1 2 3 4 5 | let book = { "main title": "Head first Javascript", } |
You can also make use of a hyphen
1 2 3 4 5 | 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.
1 2 3 4 5 6 | 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.
1 2 3 4 5 6 7 8 9 | let book = { "main title": "Eloquent JavaScript", author: { firstName: "Marijn", lastName: "Haverbeke" } }; |
In the following example, getAuthorName
is a function
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
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.
1 2 3 4 5 6 7 8 9 10 11 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | values = { 1: "One", 2: "two", 3: "three", }; console.log(values); //This is same as above values = { "1": "One", "2": "two", "3": "three", }; |
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
.
1 2 3 4 5 6 7 8 9 | var person = { firstName: "Allie", lastName: "Grater", age: 50 }; console.log(person) |
The above example does the same thing as the following example.
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | let firstName = "Allie" let lastName = "Grater" let person = { firstName, lastName }; console.log(person) //{firstName: "Allie", lastName: "Grater"} |
You can mix and match both approaches
1 2 3 4 5 6 7 8 9 10 11 12 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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( []
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 |
References
Read More