What are Object Literals? | ES6 Guide

Deepak Kumar
Sep 20 · 2 min read

Object literals are used to create an object in javascript. Enhancement in Object literals in ES2015 (ES6) release has made it a more powerful feature.

  • The object in javascript can be initialized by directly using the variable name. See Example 1 below.
  • Object’s method in ES5 requires function statement. This is no longer required in ES6, you can directly return statement. See Example 2 below.
  • Object literals key in ES6 can be dynamic. Any Express can be used to create a key.

RECAP

There are three ways of creating an object in javascript.

  • Using Object literals
  • Using new keyword.
  • By defining object constructor and then create an object constructor type.

Let’s take a look at this example to see the working of Object literals.

Object Literals Without ES6 ( ES5 Supported )

# Example 1 var username = 'dipakkr'
var name = 'Deepak Kumar'
var country = 'India'
var password = '123456'
var user = {
username : username,
name : name,
country : country,
password : password
}
# Example 2var calculate = {
sqaure : function(a) { return a*a; },
sum : function(a, b) { return a + b; }
};
console.log(calculate.square(5)); // 25
console.log(calculate.sum(4,5)); // 9

Object Literals with ES6

# Example 1const username = 'dipakkr'
const name = 'Deepak Kumar'
const country = 'India'
const password = '123456'
const user = {
username,
name,
country,
password,
};
# Example 2const calculate = {
square(a) return a*a,
sum(a, b) return a+b
}
console.log(calculate.square(5)); // 25
console.log(calculate.sum(5,7)); // 12

If you want to learn others concepts of ES6 please check out this, comprehensive guide to learn ES6.

Give some clap if you liked the article !!

Cheers!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade