Javascript Object Properties with Examples
Javascript Objects hold data items in the key-value pair. They are different from arrays were we use the index to display the value in Objects we use the key to display values.
In array, the item value may be string, integer or boolean but in the object, they have value as a string, integer or boolean and also we can specify function inside objects something which we can’t do in arrays.
Creating Objects
There are two ways of creating an empty object. First, let us learn to create an object using object()
method.
let student = Object(); console.log(student); //Console Output {}
Creating Object using curly braces.
let student = {}; console.log(student); //Console Output {}
Inserting items into the object
We need to pass items with key-value pair inside curly braces this will insert items into the object.
var obj = {"name" : "Vikas", "age" : "19"}; var student = Object(obj); console.log(student); //Console Output {name: "Vikas", age: "19"}
Inserting using the shorthand method. This method gives the same output as the above method.
var student = {"name" : "Vikas", "age" : "19"}; console.log(student); //Console Output {name: "Vikas", age: "19"}
Some more examples
Inserting items after initialization. To do that use object name followed by dot(.)
operator and specify a key name and give it a value.
var student = {"name" : "Vikas", "age" : "19"}; console.log("Before inserting new items : ",student); student.class = "PUC 2nd Year"; student.division = "A"; console.log("After inserting new items : ",student); //Console Output Before inserting new items : {name: "Vikas", age: "19"} After inserting new items : {name: "Vikas", age: "19", class: "PUC 2nd Year", division: "A"}
In the above example, the class
, division
is key and “PUC 2nd Year”, A is its values.
We also use dot(.)
operator to access the value of the particular item or using square brackets and specifying key name inside them.
student.class "PUC 2nd Year" //Console Output student.name "Vikas" //Console Output student["name"] "Vikas" //Console Output student["class"] "PUC 2nd Year" //Console Output
Updating Items inside Object
To update single item access that item using the key and assign it a value.
student.name = "John Dave"; "John Dave" //Console Output student["name"] = "Bruce Wayne"; "Bruce Wayne" //Console Output
Removing Items
Use delete
keyword to remove the item from the object.
var fruit = {"name" : "Apple", "color" : "red", "weight" : "56.75 grams", "quantity" : 15}; console.log("Before removing item 'color' ",fruit); delete fruit.color; console.log("After removing item 'color' ",fruit); //Console Output Before removing item 'color' {name: "Apple", color: "red", weight: "56.75 grams", quantity: 15} After removing item 'color' {name: "Apple", weight: "56.75 grams", quantity: 15}
When the item does not exist the object returns undefined
.