You can create a JavaScript object in a few different ways but the most common way to use an object literals. We have learned Arrow functions in the last post. Let’s look at how to define and use object literals in Modern JavaScript.
Literal initialization is very common in JavaScript. We use it for objects, arrays, string, numbers and even things like a regular expression.
Example of Object Literals
const obj = { a1: 40, a2: 50, p1() {}, p2: () => {}, };
Let’s look at the above example, you don’t need to use ‘new‘ keyword to create an object. In the above example, we have declared two properties (a1 and a2). Also, we have declared two function properties which contain Regular and Arrow function.
Dynamic Properties in Object Literals
Modern Object Literals can contain dynamics properties. Let’s see an example below.
const number = "age"; const obj = { [number]: 27 }; Console.log(obj.number); // Output = undefined Console.log(obj.age); // Output = 27
We have defined the dynamic property named ‘number‘. If you directly call obj.number then it will give you output as undefined. Because ‘number‘ is a dynamic property and it will evaluate expression first and whatever that expression evaluates will become an object’s property.
We have declared const number and its value is age. So dynamic expression will evaluate it and will become ‘age‘ property of obj. So when you call obj.age it gives you proper output as 27.
Mapping Object Property to the Variable in Scope
Another important thing you can do in the object literals is that when you want to assign the same variable name to the property with the same name in the object. You can do this in a different way. Let’s see that.
const fruit = "apple"; const obj = { fruit: fruit };
In the above code, you have we have one const variable with fruit name and another property fruit inside the object. Both have the same names so if you want to assign variable value to property then you could do as above but there is a more easy way. Let’s see below.
const fruit = "apple"; const obj = { fruit, };
Only fruit property name will be enough. You don’t need to assign again because it has the same naming convention.
In the upcoming article, we will see what is destructing in modern JavaScript.