Creating Objects
Creating objects in JavaScript is easy. The language provides syntax known as object literal notation for quickly creating objects. Object literals are denoted by curly braces. The following example creates an empty object with no properties.var object = {};
Inside of the curly braces, properties and their values are specified as a list of key/value pairs. Keys can be strings or identifiers, while values can be any valid expression. The list of key/value pairs is comma delimited, with each key and value separated by a colon. The following example creates an object with three properties using literal notation. The first property, foo
, holds the number one. The second property, bar
, is specified using a string, and also stores a string value. The third property, baz
, stores an empty object.
var object = {
foo: 1,
"bar": "some string",
baz: {
}
};
Note the use of whitespace in the previous example. Each property has been written on a separate line and indented. The entire object could have been written on a single line, but the code is more readable in this format. This is especially true for objects with many properties or nested objects.
Accessing Properties
JavaScript provides two notations for accessing object properties. 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. The following example shows how dot notation is used to read from and write to a property. Ifobject.foo
initially held the value one, then its value would become two after executing this statement. Note that if object.foo
did not already have a value, then it would be undefined
.
object.foo = object.foo + 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. The previous example of dot notation has been rewritten below to use bracket notation. While the code may look different, it is functionally equivalent to the previous example.
object["foo"] = object["foo"] + 1;
Bracket notation is more expressive than dot notation because it allows a variable to specify all or part of the property name. This is possible because the JavaScript interpreter automatically converts the expression within the square brackets to a string, and then retrieves the corresponding property. The following example shows how property names can be created on the fly using bracket notation. In the example, the property name foo
is created by concatenating the contents of variable f
, with the string "oo"
.
var f = "f";
object[f + "oo"] = "bar";
Bracket notation also allows property names to contain characters that are forbidden in dot notation. For example, the following statement is completely legal in bracket notation. However, if you tried to create the same property name in dot notation, you would encounter a syntax error.
object["!@#$%^&*()."] = true;
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 namedbaz
, which contains another object named foo
, which has a property named bar
that holds the value five.
var object = {
baz: {
foo: {
bar: 5
}
}
};
The following expressions access the nested property, bar
. The first expression uses dot notation, while the second expression uses square bracket notation. The third expression combines both notations to achieve the same result.
object.baz.foo.bar;
object["baz"]["foo"]["bar"];
object["baz"].foo["bar"];
Expressions like the ones shown in the previous example can cause performance to suffer if used improperly. Evaluating each dot or bracket expression takes time. If the same property is used multiple times, then it makes more sense to access the property once, and then store the value in a local variable for all future uses. The following example uses bar
many times within a loop. However, instead of wasting time computing the same value over and over, bar
is stored in a local variable.
var bar = object.baz.foo.bar;
var count = 0;
for (var i = 0; i < 100000; i++) {
count += bar;
// better than count += object.baz.foo.bar;
}
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. The following example shows how this is accomplished.var object = {
sum: function(foo, bar) {
return foo + bar;
}
};
Methods can also be invoked using dot and bracket notation. The following example invokes the sum()
method from the previous example using both notations.
object.sum(1, 2);
object["sum"](1, 2);
Adding Properties and Methods
Object literal notation is useful for creating new objects, but it cannot add properties or methods to existing objects. Fortunately, adding new data to an object is as simple as creating an assignment statement. The following example creates an empty object. Two properties,foo
and bar
, and a method, baz
, are then added using assignment statements. Note, that this example uses dot notation, but bracket notation would work equally as well.
var object = {};
object.foo = 1;
object.bar = null;
object.baz = function() {
return "hello from baz()";
};
Conclusion
This article has covered the basics of JavaScript object syntax. It is crucial to have a solid understanding of this material, as it serves as a foundation for the rest of the language. They say you must first walk before you can run. Well, in the world of JavaScript, you must first understand objects before you can understand object-oriented programming.Frequently Asked Questions (FAQs) about JavaScript Object Syntax
What is the difference between dot notation and bracket notation in JavaScript object syntax?
In JavaScript, objects are collections of key-value pairs. You can access these values using either dot notation or bracket notation. Dot notation is more straightforward and easier to read. It’s used when you know the property name. For example, if you have an object ‘person’ with a property ‘name’, you can access it like this: person.name.
Bracket notation, on the other hand, is more flexible. It allows you to access properties using variables or property names that may not be valid identifiers. For instance, if a property name has spaces or special characters, or it’s a number, you can access it like this: person[‘property name’].
How can I add properties to an existing JavaScript object?
You can add properties to an existing JavaScript object using either dot notation or bracket notation. For dot notation, you simply use the syntax object.property = value. For bracket notation, the syntax is object[‘property’] = value. In both cases, if the property does not already exist on the object, it will be added.
How can I delete properties from a JavaScript object?
You can delete properties from a JavaScript object using the ‘delete’ operator. The syntax is delete object.property for dot notation and delete object[‘property’] for bracket notation. This will remove the property and its value from the object.
What are methods in JavaScript objects?
Methods are functions that are stored as object properties. They are used to perform actions that utilize the data of the object. You can define a method in an object using function syntax, like this: object.methodName = function() { /* code */ }.
How can I iterate over the properties of a JavaScript object?
You can iterate over the properties of a JavaScript object using a ‘for…in’ loop. This loop will iterate over all enumerable properties of the object, including those inherited from the prototype chain. The syntax is: for (var property in object) { /* code */ }.
What is the ‘this’ keyword in JavaScript objects?
The ‘this’ keyword in JavaScript objects refers to the object it belongs to. Inside a method, ‘this’ refers to the owner object. In a constructor function, ‘this’ refers to the newly created object.
What are constructor functions in JavaScript?
Constructor functions in JavaScript are special functions used to create objects of the same type. They are named with a capital letter to distinguish them from regular functions. The ‘new’ keyword is used to call a constructor function and create a new object.
What is object prototype in JavaScript?
Every JavaScript object has a prototype. The prototype is also an object, and all objects inherit properties and methods from their prototype. This is a powerful feature of JavaScript, as it allows you to add new properties or methods to all instances of an object type.
How can I check if a property exists in a JavaScript object?
You can check if a property exists in a JavaScript object using the ‘in’ operator or the ‘hasOwnProperty’ method. The ‘in’ operator returns true if the property exists in the object or its prototype chain. The ‘hasOwnProperty’ method returns true only if the property exists in the object itself.
What is object destructuring in JavaScript?
Object destructuring in JavaScript is a feature that allows you to extract properties from objects and bind them to variables. This can make your code more concise and readable. The syntax is: var { property1, property2 } = object.
Colin Ihrig is a software engineer working primarily with Node.js. Colin is the author of Pro Node.js for Developers, and co-author of Full Stack JavaScript Development with MEAN. Colin is a member of the Node.js Technical Steering Committee, and a hapi core team member. Colin received his Bachelor of Science in Engineering, and Master of Science in Computer Engineering from the University of Pittsburgh in 2005 and 2008, respectively.