What are objects in JavaScript?
Suppose if you are in a situation of using same and repeated variables again and again, to reduce this kind of again and again declaration of same kind of variable objects will reduce this problem in programming, it a kind of key and value pairs, it does not allow repeated duplicated keys and you can store primitive and not primitive data types as values to the objects keys.
How to create objects
JavaScript allows us to create objects in several ways, for example object literals, object constructors and many more ways.
Creating object using the object literals
const obj1 = {
name:”yukihiro matsumoto”,
language: “Japanese”
}
here each key should be separated by the commas, it allows to identify each key and values respectively.
To access the values in the object we have to use the object variable along with dot and the you can specify which key why want to call
console.log(“obj1.name”)
// yukihiro matsumoto
console.log(“obj1.language ”)
// Japanese
Why are we using const for objects?
Why do you notice that we are using const for the object variables, then you may ask why you are using const? By using const, are we able to change the values of any of them?
Let us see one by them, why const?
Const will key the object reference same and we are only changing the values inside the same references, but if we use any other variable keyword it will allow to change the variable’s references
In any way we are able to modify and object key values.
Creating objects form existing variables
let say you already have some of the variables
const a = “Apple”;
const b = “Ball”;
const c = “cat”;
if you want to use this variable’s values in your new object you can use its values
const abc = {
a : a,
b:b,
c:c
}
instead also we can able to use the short hand notation for creating objects using this variable in for the object creation
const abc = {
a , b, c
};
let we see how to change the values of the keys
const obj1 = {
name:”yukihiro matsumoto”,
language: “Japanese”
}
obj1.name = “Brendan Eich”;
obj1.language = “English”;
console.log(obj1)
// { name : “Brendan Eich” , language : “English” }
let we see the how to create the Object using the object constructor
const obj2 = new Object();
obj2.name = “Rasmus Lerdorf”;
obj2.language = “English”;
// { name : “Rasmus Lerdorf” , language : “English” }
Top comments (0)