JavaScript Object Properties

JavaScript Object Properties with Examples

In this article, I am going to discuss JavaScript Object Properties with Examples. Please read our previous article where we discussed Creating JavaScript objects using Object Factories. At the end of this article, you will understand everything about JavaScript Object Properties.

JavaScript Object Properties

We have already learned a small portion of object properties while evaluating the object’s features and different ways to create objects. JavaScript Object properties contain the below features:

1. JavaScript is designed on a simple object-based paradigm(language). An object is a collection of properties.

2. An object property is an association between a name (or key) and a value. A value of a property can be either Property (variable/field) or Function (method).

3. An object is a complex data type in JavaScript that is used to store any combination of data in a simple key-value pair. Each key-value pair is called a property. Data inside objects are unordered hence index concept is not applicable like Array, and the values can be of any type.

4. JavaScript is template based not class-based. That means, in JavaScript, we don’t have to create a class to get an object instead we direct create objects.

5. JavaScript objects are simple maps from names (or keys) to values (properties) and functions (methods);

6. Objects are containers with properties. properties can contain anything such as Even functions or other objects

7. JavaScript object is a list of values that are written as key: value pairs within a curly bracket {…}, with the keys and the values separated by colons. Property has a key (also known as “name” or “identifier”) before the colon “:” and a value to the right of it.

8. When we have multiple properties, each property is separated by comma (,) except for the last property there will not be any comma after the last property.

9. All keys/Properties in JavaScript objects are strings and can be only a string or symbols. If it’s not a string. It gets cast/converted to a string unless they’re Symbols. This means that even though we can create an object {1: ‘is the real number’}, the key here, 1 gets turned into the string ‘1’. Values can be of any type. Whereas Symbol doesn’t get converted to string it remains as it is (we will be learned about Symbol in Symbol Chapter.

10. All the object keys are unique, but values are not.

If we use a string with space or hyphen (-) or that starts with a number for a property name, we need to use quotes around the property name. That can only be accessed using the square bracket notation [ ].

var widget = {
cost$: 3.14,
     on sale": true
};

In JavaScript objects contain propertyName: propertyValue pairs.

11. Properties and methods can change at any time. Added by assigning to a new name and removed by assigning null to the name.

12. JavaScript object properties can be accessed in two ways: objectName.propertyName and objectName[‘propertyName’]

13. Same as like other JavaScript variables, both the object name (which could be a normal variable), as well as property name/key, are case sensitive

JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names. We can also access the object properties by using a string value that is stored in a variable.

const tutorial = 'course';
let lecture = {
              [tutorial]: 'JavaScript',
              version: 'ES6'
              }
              console.log(lecture); //{course: "JavaScript", version: "ES6"} 
              console.log(lecture['course']); //JavaScript-bracket notion
              console.log(lecture.course); //JavaScript- dot notation
              console.log(lecture[tutorial]); //JavaScript
              console.log(lecture['tutorial']); //undefined
              console.log(lecture.tutorial); //undefined

14. Object.assign — recursive shallow overwrite for properties from the target, …objects

15. Object.getOwnPropertySymbols — returns all own property symbols found on an object

16. JavaScript objects are mutable, meaning their contents can be changed, even when they are declared as const. new properties can be added, and existing property values can be changed or deleted.

17. Objects are one of the core concepts in JavaScript. JavaScript objects are containers for named(key) values called properties or methods.

How to access Object Properties in JavaScript?

An object can be created with curly brackets {…} with a list of properties. A property is a “key: value” pair, where the key is a string (also called a “property name”), and value can be any data type, like strings, numbers, Booleans, or complex data types like arrays, functions, and other objects. with the names(keys) and the values separated by colons (:). We can access the properties of the object in two ways,

1. By dot operator/ dot notation (.): Here we cannot take quotes (single (‘ ‘) or double quotes (” “)).
objectName.propertyName

2. By Square brackets/ bracket notation/ Array-like notation ([]): Here quotes (single (‘ ‘) or double quotes (” “)) are mandatory.
objectName[‘propertyName’] – valid
objectName[propertyName] — Uncaught ReferenceError: propertyName is not defined

Objects contain properties, which are used to describe an object. Values of object properties can either contain primitive data types, like strings, numbers, Booleans, or other objects/complex data types like arrays, functions, and other objects.

In plain English, a JavaScript object literal also called an object initializer, is a list of key-value pairs comma-separated inside of curly braces {}, with the keys and the values separated by colons (:). Key-value pairs of an object are also referred to as properties. Those values can be properties and functions. All the keys are unique, but values are not.

The object literal notation is mainly an array of key: value pairs, with a colon (:) separating the keys and values, and a comma (,) after every key: value pair, except for the last item we don’t need to put a comma after that, just like a regular array. Values created with anonymous functions are methods of an object and simple values are properties. We can declare properties when creating an object or later. We can have zero or more properties separated by commas (,).

Syntax:
let objectName = {};// "object literal" syntax /create an empty object
or
//initialize an object with properties/key-value pairs
var objectName = { property1: value1, property2: value2....propertyN: valueN }

As we can see, property and value are separated by : (colon). The curly braces ({}) are an object. We just have created our first object. We can also initialize an object with key-value pairs with {key: value} syntax

Properties of a JavaScript object can be accessed using a dot notation(.) or bracket notation [ ]. For Example, objectName.propertyName or objectName[‘propertyName’] will give us the value.

All members of an object literal in JavaScript, both properties and functions, are public. The only place we can put private members is inside of a function. We can declare the properties and methods listed using cleaner Object Literal syntax:

Syntax:
var myObject = {
            myProperty: value,
            secondProperty: value,
            myMethod: function () {
                //code here
            },
            secondMethod: function () {
                //more code
            }
        }
Rules of the road in Naming and Creating JavaScript Object Properties

JavaScript object key names/property names must follow some rules to be valid

1. Property names or Key names must either be strings or valid identifiers or variable names (i.e.: special characters such as -, +, spaces are not allowed in property names that are not strings).

// Example of invalid key names
const trainTimeTable = {
    platform num: 9, // Invalid because of the space between words.
    30 - 10 + 2: 40, // Expressions cannot be keys.
    + compartment: 'AC' // The use of a + sign is invalid unless it is enclosed in quotations.
}

2. The property names do not need to be enclosed in a quote (single (‘ ‘) or double quotes (” “)) until they are reserved words of JavaScript, or if they have spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number. For example, complexObj.$1 is valid, while complexObj.1 is not.

const complexObj = {};
complexObj.$1 = 'test';
console.log(complexObj.$1);  // 'test'
complexObj.1 = 'series';     // SyntaxError
console.log(complexObj.1);   // SyntaxError

3. Separate the property name and property value with a colon (:) :

var covid = {
    year: 2020
};

4. A property name can be any string, but we usually stick with valid variable names:

var widget = {
    cost$: 3.14,
    "on sale": true
};

Notice that if we use a string with a space in it for a property name, we need to use quotes around the name. That can only be accessed using the square bracket notation [ ].

5. No two properties in an object can have the same name:

var weatherForecast = {
    highTemp: 45,
    highTemp: 40 //this won’t work
};

If the property already exists, its value will be replaced with a newly added one.

6. Separate each property name and values pair with a comma:

var bike = {
    model: 'pulsar',
    color: 'black'
};

7. Don’t use a comma after the last property value:

var month = {
    name: 'April',
    season: 'summer'  //no comma needed here.
};
Access the Properties by dot operator/ dot notation (.)
Example: JavaScript Objects, access an object using dot notation — object.property
<html>
<head>
    <title>JavaScript Objects, access an object using dot notation-- object.property example</title>
</head>
<body>
    <script>
        console.log('sample1 code with object literal syntax');
        //sample1 code
        //Create an object
        let student = {};
        student.name = "John";// by key "name" store value "John"
        student.rollNo = 10; // by key "rollNo" store value 10

        console.log("student object: ", student)
        console.log("student object length: ", Object.getOwnPropertyNames(student).length)
        console.log("student Object literal type? : ", typeof student);// object

        //display data
        console.log("Display student object data - with dot notation-->Property name value is: " + student.name);
        console.log("Display student object data - with dot notation-->Property rollNo value is: " + student.rollNo);
        console.log("Display student object data - having name property with value: " + student.name + ", with 2nd property rollNo having value: "
            + student.rollNo);
        console.log("student object data -->Property name length is: " + student.name.length); //4

        console.log("********************");
        console.log('sample2 code with initialize an object with key-value pairs syntax');
        //sample2 code
        //initialize an object with key-value pairs, create an object
        let professor = {
            name: 'Johnson',
            course: 'JavaScript',
            technology: 'Web development'
        }

        console.log("professor object: ", professor)
        console.log("professor object length: ", Object.getOwnPropertyNames(professor).length)
        console.log("professor Object literal type? : ", typeof professor);// object

        //display data
        console.log("Display professor object data - with dot notation-->Property name value is: " + professor.name);
        console.log("Display professor object data - with dot notation-->Property course value is: " + professor.course);
        console.log("Display professor object data - with dot notation-->Property technology value is: " + professor.technology);
        console.log("Display professor object data - having name property with value: " + professor.name + ", with 2nd property course having value: "
            + professor.course + " and the last property technology with value as " + professor.technology);
        console.log("professor object data -->Property name length is: " + professor.name.length); //7
        console.log("professor object data -->Property course length is: " + professor.course.length); //10

    </script>
</body>
</html>
Output:

Access the Properties by dot operator/ dot notation (.)

We can add properties dynamically in an object, including after we have created the object. Here we have added the dynamic property student.name to the object student. After creating the object, we can get the properties of the object with dot notation or bracket/array notation.

In the above example, Sample1 code contains 2 properties to student object, in the first property name is the key and John is the value and in the second property, rollNo is the key and 10 is the value. We can get the value of name property with the student.name, and rollNo property with student.rollNo.

Similarly, in Sample2 code there are 3 properties assign to the professor object, in the first property name is the key and Johnson is the value, the 2nd property has the course as key and JavaScript as value. Later for 3rd property, we have technology as the key and Web development as the value.

JavaScript has a built-in length property that is used to count the number of characters in a property or string.

Hence when we use the inbuilt length property in student object for name property to get its length i.e.: student.name.length It returns the count of the number of characters in a name property. since name property is string type so we can use the length property. Inbuilt length property works only for string. Similarly, we can check the length of name and course properties length of professor object i.e.: professor.name.length & professor.course.length

Access the Properties by Square brackets/ bracket notation/ Array-like notation ([])
Example: JavaScript Objects, access an object using bracket notation– object[“property”]
<html>
<head>
    <title>JavaScript Objects, access an object using bracket notation-- object["property"] example</title>
</head>
<body>
    <script>
        console.log('sample1 code with object literal syntax');
        //sample1 code
        //Create an object
        let student = {};
        student.name = "John";// by key "name" store value "John"
        student.rollNo = 10; // by key "rollNo" store value 10

        console.log("student object: ", student)
        console.log("student object length: ", Object.getOwnPropertyNames(student).length)
        console.log("student Object literal type? : ", typeof student);// object

        //display data
        console.log("Display student object data - with bracket notation-->Property name value is: " + student["name"]);
        console.log("Display student object data - with bracket notation-->Property rollNo value is: " + student["rollNo"]);
        console.log("Display student object data - having name property with value: " + student["name"] + ", with 2nd property rollNo having value: "
            + student["rollNo"]);
        console.log("student object data -->Property name length is: " + student['name'].length); //4

        console.log("********************");
        console.log('sample2 code with initialize an object with key-value pairs syntax');
        //sample2 code
        //initialize an object with key-value pairs, create an object
        let professor = {
            name: 'Johnson',
            course: 'JavaScript',
            'technology type': 'Web development'
        }

        console.log("professor object: ", professor)
        console.log("professor object length: ", Object.getOwnPropertyNames(professor).length)
        console.log("professor Object literal type? : ", typeof professor);// object

        //display data
        console.log("Display professor object data - with bracket notation-->Property name value is: " + professor["name"]);
        console.log("Display professor object data - with bracket notation-->Property course value is: " + professor["course"]);
        console.log("Display professor object data - with bracket notation-->Property technology type value is: " + professor['technology type']);
        console.log("Display professor object data - having name property with value: " + professor['name'] + ", with 2nd property course having value: "
            + professor['course'] + " and the last property technology type with value as " + professor['technology type']);
        console.log("professor object data -->Property name length is: " + professor['name'].length); //7
        console.log("professor object data -->Property course length is: " + professor['course'].length); //10
        console.log("professor object data -->Property technology type length is: " + professor['technology type'].length); //15

    </script>
</body>
</html>  
Output:

Access the Properties by Square brackets/ bracket notation/ Array-like notation ([])

We can add properties dynamically in an object, including after we have created the object. Here we have added the dynamic property student.name to the object student. After creating the object, we can get the properties of the object with dot notation or bracket/array notation.

In the above example, Sample1 code contains 2 properties to student object, in the first property name is the key and John is the value and in the second property, rollNo is the key and 10 is the value. We can get the value of name property with the student[“name”], and rollNo property with student[“rollNo”].

Similarly, in Sample2 code there are 3 properties assign to the professor object, in the first property name is the key and Johnson is the value, the 2nd property has the course as key and JavaScript as value. Later for the 3rd property, we have technology type as the key and Web development as the value.

If we noticed the 3rd property contains spaces in that hence its quoted. i.e.: ‘technology type’. The way of accessing such properties using the bracket notation would be i.e.: professor [‘technology type’].

We already learned that in rules for naming properties that the property names do not need to be enclosed in a quote (single (‘ ‘) or double quotes (” “)) until they are reserved words of JavaScript, or if they have spaces or special characters (anything other than letters, numbers, and the _ and $ characters), or if they start with a number.

JavaScript has a built-in length property that is used to count the number of characters in a property or string.

Hence when we use the inbuilt length property in student object for name property to get its length i.e.: student[‘name’].length It returns the count of the number of characters in a name property. since name property is string type so we can use the length property. Inbuilt length property works only for string. Similarly, we can check the length of name, course, and technology type properties length of professor object i.e.: professor[‘name’].length, professor[‘course’].length & professor[‘technology type’].length

JavaScript Object Properties with Examples

In the next article, I am going to discuss JavaScript Object Nested Properties with Examples. Here, in this article, I try to explain JavaScript Object Properties with Examples and I hope you enjoy this JavaScript Object Properties article.

Leave a Reply

Your email address will not be published.