Object literals basic.
1) Javascript Objects:
JavaScript object is a non-primitive data-type that allows you to store multiple collections of data. You do not need to create classes in order to create objects.
The syntax to declare an object is:
const object_name = {
key1: value1, //---> properties
key2: value2
}
2)EXAMPLE 1: Creating basic object literals
3)EXAMPLE 2: Nested object inside an already existing object
1) Here, the object "food :" in line no.4 is a nested object inside the already existing object "animal" in line no.1. Notice that the parent object uses ' = ' sign while the nested object uses ' : ' to write their properties.
2) In line no.9 console.log(animal.legs) is used to access the legs property of the "animal" class and print its' value (i.e., 4) in the console.
3) The syntax to access the properties of the nested object is :
" parentobjectName.nestedobjectName.propertyName " . In line no.10, "console.log(animal.food.carnivore)" is used to access the carnivore property of the nested class food and print its' value (i.e., true) in the console.
4) EXAMPLE 3: Mutating/ Changing the value of properties of the objects.
1) Just like arrays, we can mutate the value of the object property by using this syntax:
" objectName.propertyName = New value" .
2) In line no.11 we have changed the value of legs property from 4 to 6 and in line no.12 we are printing it in the console.
3) So the output for line no.9 before mutating = 4 , and output for line no.12 = 6.
5) EXAMPLE 4: Another syntax for accessing the properties of the object ( objectName["propertyName"] syntax
1) In all the previous examples we have the dot syntax ( objectName.propertyName) to access the properties, there's another syntax too, and its' square box syntax
( objectName["propertyName"] ).
2) In line no.12 we used the syntax console.log(animal["legs']), to access legs property of the animal object and print its' value (i.e., 6) to the console.
6) EXAMPLE 5: Adding brand new property: value pairs to the object.
1) Here in line no.13, we are adding a brand new property tail with the value 1 to the animal object and the syntax is animal.tail = 1.
2) In line no.14, we are printing the entire new object with the new property in the console.
7)
8)
9)
10)










Comments
Post a Comment