Modern JavaScript for React: Object Literals – Part 3

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.

Modern Javascript Object Literals



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

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.

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.

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 propety then you could do as above but there is a more easy way. Let’s see below.

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.

Tutorial Funda

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *