JavaScript Object Syntax
In this article, I’ll explain objects in JavaScript.
- Objects are composite data types that are built from primitive and other objects.
- An object’s building blocks are commonly referred to as its properties.
- Properties are used to describe some aspect of an object.
- For example, a property can describe the color of a horse.
Creating Objects
- The language provides syntax known as object literal notation for quickly creating objects.
- Object literals are denoted by curly braces.
For example:
- Inside of the curly braces, properties and their values are specified as a list of key/value pairs.
- The following example creates an object with three properties using literal notation.
- The first property,abhi, holds the number ten.
- The second property, jeet, is specified using a string, and also stores a string value.
- The third property, bittoo, stores an empty object.
- var object = { abhi: 10,
- "jeet": "hello world..",
- bittoo: {}
- };
Accessing Properties
- JavaScript provides two notations for accessing object properties.
- Dot Notation
- Bracket Notation
- The first, and most common, is known as dot notation.
- Under dot notation, a property is accessed by giving the host object’s name, followed by a period (or dot), followed by the property name.
- If object.abhi initially held the value ten, then its value would become eleven after executing this statement.
- Note that if an object.abhi did not already have a value, then it would be undefined.
- object.abhi = object.abhi+ 1;
- The alternate syntax for accessing object properties is known as bracket notation.
- In bracket notation, the object name is followed by a set of square brackets. Inside the square brackets, the property name is specified as a string.
For example
- object["abhi"] = object["abhi"] + 1;
Accessing Nested Properties
- Properties of nested objects can be accessed by chaining dot and/or bracket references together.
For example, the following object contains a nested object named bittoo, that contains another object named abhi, that has a property named jeet that holds the value six.
- var object = {
- bittoo: {
- abhi: {
- jeet: 6
- }
- }
- };
- The following expressions access the nested property, jeet.
- The first expression uses dot notation,
- The second expression uses square bracket notation.
- The third expression combines both notations to do the same result.
- object.bittoo.abhi.jeet;
- object["bittoo"]["abhi"]["jeet"];
- object["bittoo"].abhi["jeet"];
Functions as Methods
- When a function is used as an object property, it is called a method.
- Like properties, methods can also be specified in object literal notation.
For example
- var object = {
- sum: function (abhi, jeet) {
- return abhi + jeet;
- }
- };
- Methods can also be invoked using dot and bracket notation.
For example
- object.sum(10, 20);
- object["sum"](10, 20);