”;
JavaScript supports extending data types. JavaScript objects are a great way to define custom data types.
An object is an instance which contains a set of key value pairs. Unlike primitive data types, objects can represent multiple or complex values and can change over their life time. The values can be scalar values or functions or even array of other objects.
The syntactic variations for defining an object is discussed further.
Object Initializers
Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object.
var identifier = { Key1:value, Key2: function () { //functions }, Key3: [“content1”,” content2”] }
The contents of an object are called properties (or members), and properties consist of a name (or key) and value. Property names must be strings or symbols, and values can be any type (including other objects).
Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation.
Following is the syntax for accessing Object Properties.
objectName.propertyName
Example: Object Initializers
var person = { firstname:"Tom", lastname:"Hanks", func:function(){return "Hello!!"}, }; //access the object values console.log(person.firstname) console.log(person.lastname) console.log(person.func())
The above Example, defines an object person. The object has three properties. The third property refers to a function.
The following output is displayed on successful execution of the above code.
Tom Hanks Hello!!
In ES6, assigning a property value that matches a property name, you can omit the property value.
Example
var foo = ''bar'' var baz = { foo } console.log(baz.foo)
The above code snippet defines an object baz. The object has a property foo. The property value is omitted here as ES6 implicitly assigns the value of the variable foo to the object’s key foo.
Following is the ES5 equivalent of the above code.
var foo = ''bar'' var baz = { foo:foo } console.log(baz.foo)
The following output is displayed on successful execution of the above code.
bar
With this shorthand syntax, the JS engine looks in the containing scope for a variable with the same name. If it is found, that variable’s value is assigned to the property. If it is not found, a Reference Error is thrown.
The Object() Constructor
JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
Following is the syntax for defining an object.
var obj_name = new Object(); obj_name.property = value; OR obj_name["key"] = value
Following is the syntax for accessing a property.
Object_name.property_key OR Object_name["property_key"]
Example
var myCar = new Object(); myCar.make = "Ford"; //define an object myCar.model = "Mustang"; myCar.year = 1987; console.log(myCar["make"]) //access the object property console.log(myCar["model"]) console.log(myCar["year"])
The following output is displayed on successful execution of the above code.
Ford Mustang 1987
Unassigned properties of an object are undefined.
Example
var myCar = new Object(); myCar.make = "Ford"; console.log(myCar["model"])
The following output is displayed on successful execution of the above code.
undefined
Note − An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
Properties can also be accessed by using a string value that is stored in a variable. In other words, the object’s property key can be a dynamic value. For example: a variable. The said concept is illustrated in the following example.
Example
var myCar = new Object() var propertyName = "make"; myCar[propertyName] = "Ford"; console.log(myCar.make)
The following output is displayed on successful execution of the above code.
Ford
Constructor Function
An object can be created using the following two steps −
Step 1 − Define the object type by writing a constructor function.
Following is the syntax for the same.
function function_name() { this.property_name = value }
The ‘this’ keyword refers to the current object in use and defines the object’s property.
Step 2 − Create an instance of the object with the new syntax.
var Object_name= new function_name() //Access the property value Object_name.property_name
The new keyword invokes the function constructor and initializes the function’s property keys.
Example − Using a Function Constructor
function Car() { this.make = "Ford" this.model = "F123" } var obj = new Car() console.log(obj.make) console.log(obj.model)
The above example uses a function constructor to define an object.
The following output is displayed on successful execution of the above code.
Ford F123
A new property can always be added to a previously defined object. For example, consider the following code snippet −
function Car() { this.make = "Ford" } var obj = new Car() obj.model = "F123" console.log(obj.make) console.log(obj.model)
The following output is displayed on successful execution of the above code.
Ford F123
The Object.create Method
Objects can also be created using the Object.create() method. It allows you to create the prototype for the object you want, without having to define a constructor function.
Example
var roles = { type: "Admin", // Default value of properties displayType : function() { // Method which will display type of role console.log(this.type); } } // Create new role type called super_role var super_role = Object.create(roles); super_role.displayType(); // Output:Admin // Create new role type called Guest var guest_role = Object.create(roles); guest_role.type = "Guest"; guest_role.displayType(); // Output:Guest
The above example defines an object -roles and sets the default values for the properties. Two new instances are created that override the default properties value for the object.
The following output is displayed on successful execution of the above code.
Admin Guest
The Object.assign() Function
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Following is the syntax for the same.
Object.assign(target, ...sources)
Example − Cloning an Object
"use strict" var det = { name:"Tom", ID:"E1001" }; var copy = Object.assign({}, det); console.log(copy); for (let val in copy) { console.log(copy[val]) }
The following output is displayed on successful execution of the above code.
Tom E1001
Example − Merging Objects
var o1 = { a: 10 }; var o2 = { b: 20 }; var o3 = { c: 30 }; var obj = Object.assign(o1, o2, o3); console.log(obj); console.log(o1);
The following output is displayed on successful execution of the above code.
{ a: 10, b: 20, c: 30 } { a: 10, b: 20, c: 30 }
Note − Unlike copying objects, when objects are merged, the larger object doesn’t maintain a new copy of the properties. Rather it holds the reference to the properties contained in the original objects. The following example explains this concept.
var o1 = { a: 10 }; var obj = Object.assign(o1); obj.a++ console.log("Value of ''a'' in the Merged object after increment ") console.log(obj.a); console.log("value of ''a'' in the Original Object after increment ") console.log(o1.a);
The following output is displayed on successful execution of the above code.
Value of ''a'' in the Merged object after increment 11 value of ''a'' in the Original Object after increment 11
Deleting Properties
You can remove a property by using the delete operator. The following code shows how to remove a property.
Example
// Creates a new object, myobj, with two properties, a and b. var myobj = new Object; myobj.a = 5; myobj.b = 12; // Removes the ‘a’ property delete myobj.a; console.log ("a" in myobj) // yields "false"
The following output is displayed on successful execution of the above code.
false
The code snippet deletes the property from the object. The example prints false as the in operator doesn’t find the property in the object.
Comparing Objects
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. This is because, they point to a completely different memory address. Only those objects that share a common reference yields true on comparison.
Example 1 − Different Object References
var val1 = {name: "Tom"}; var val2 = {name: "Tom"}; console.log(val1 == val2) // return false console.log(val1 === val2) // return false
In the above example, val1 and val2 are two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false.
Example 2 − Single Object Reference
var val1 = {name: "Tom"}; var val2 = val1 console.log(val1 == val2) // return true console.log(val1 === val2) // return true
In the above example, the contents in val1 are assigned to val2, i.e. the reference of the properties in val1 are shared with val2. Since, the objects now share the reference to the property, the equality operator will return true for two distinct objects that refer to two different memory addresses. Hence on comparison for equality, the operator will return false.
Object De-structuring
The term destructuring refers to breaking up the structure of an entity. The destructuring assignment syntax in JavaScript makes it possible to extract data from arrays or objects into distinct variables. The same is illustrated in the following example.
Example 1
When destructuring an object the variable names and the object property names must match.
<script> let student = { rollno:20, name:''Prijin'', cgpa:7.2 } //destructuring to same property name let {name,cgpa} = student console.log(name) console.log(cgpa) //destructuring to different name let {name:student_name,cgpa:student_cgpa}=student console.log(student_cgpa) console.log("student_name",student_name) </script>
The output of the above code will be as seen below −
Prijin 7.2 7.2 student_name Prijin
Example 2
If the variable and assignment are in two different steps, then the destructuring object syntax will be surrounded by () as shown in the example ({rollno} = student) −
<script> let student = { rollno:20, name:''Prijin'', cgpa:7.2 } // destructuring to already declared variable let rollno; ({rollno} = student) console.log(rollno) // assign default values to variables let product ={ id:1001,price:2000} //discount is not product property let {id,price,discount=.10} = product console.log(id) console.log(price) console.log(discount) </script>
The output of the above code will be as mentioned below −
20 1001 2000 0.1
Example 3
The below example shows destructuring using the rest operator and how to destruct nested objects.
<script> // rest operator with object destructuring let customers= { c1:101, c2:102, c3:103 } let {c1,...others} = customers console.log(c1) console.log(others) //nested objects let emp = { id:101, address:{ city:''Mumbai'', pin:1234 } } let {address} = emp; console.log(address) let {address:{city,pin}} = emp console.log(city) </script>
The output of the above code will be as mentioned below −
101 {c2: 102, c3: 103} {city: "Mumbai", pin: 1234} Mumbai
”;