An object is a collection of key-value pairs.
Here's a snippet of an object with one property and one function.
const person = {
name: "Harsha",
greet: (msg, name) => {
console.log(message + "" + name + "!");
}
}
With ES6
, we got some enhancements to object literals.
Key Shorthand and Function Shorthand
const name = 'Harsha'
const age = 19
const person = {
name: name,
age: age
greet: function () => {
console.log("Hi")
}
}
In the above code, we are creating an object person with name and age property and we assigned them the values of our constant variables name
and age
. And we also have a greet property that has a function assigned to it.
Javascript introduced a shorthand notation to set object keys that have the same name as the variable you are assigning the value with. And also we can omit the function keyword in the object and define functions in a similar way as we do in class.
With the key shorthand notation and function shorthand notation, the above code can be written as:
const name = 'Harsha'
const age = 19
const person = {
name,
age,
greet() => {
console.log("Hi")
}
}
As you can see the above code looks way better, cleaner, and easier in terms of writing.
Dynamic Properties
With ES6
we can directly use our variable as a property in the object literal.
const dynamicKey="name"
const object = {
[dynamicKey]: "Harsha"
}
As you can see in the above example, we need to wrap our computed property names in the square brackets. The above object is the same as
const object = {
"name": "Harsha"
}
Top comments (1)
What about set, get and _?