How to create object properties in JavaScript ?
JavaScript is based on a basic object-oriented framework. A property is a link between a key and a value, while an object is a set of properties. A JavaScript object is a collection of properties that are not in any particular sequence.
Value of javascript properties can also be a method or function. Object properties can be updated or modified, added and deleted. sometimes properties are static and can’t be modified. In this article let’s see how to access and create object properties.
Syntax: For accessing an object property using the following ways:
objectName.property; // Using dot notation objectName['propertyName'] // Using property name // Here expression which relates to property name objectName[expression]
Creating object Properties:
Example 1: In the below code, we create an object and add properties and their associated values using the dot operator.
Javascript
<script> let student = new Object(); student.name = "ishika" ; student.section = "b9" ; student.cgpa = "9.52" ; student.branch = "CSE" ; console.log(student); </script> |
Output:
Example 2: The below illustration is written using an object initialiser, object initialiser is a comma-delimited list, where there are pairs of property names and associated values of an object, enclosed in curly braces ({}). We further access the property values using the dot operator.
Javascript
<script> let student = { name: "pratyusha" , section: "b9" , cgpa: "9" , branch: "CSE" , }; console.log(student.name); console.log(student.section); console.log(student.cgpa); </script> |
Output:
Access object properties:
Example: Following example covers the three ways to access properties are demonstrated in the code.
Javascript
<script> let student = new Object(); student.name = "ishika" ; student.section = "b9" ; student.cgpa = "9.52" ; student.branch = "CSE" ; console.log(student); // way 1 console.log(student.name); // way 2 console.log(student[ "name" ]); // way 3 let str = "name" ; console.log(student[str]); </script> |
Output:
Please Login to comment...