As you embark on this journey through the world of JavaScript objects, you'll quickly discover that objects are a fundamental and powerful part of the language. They are the building blocks that allow you to create complex data structures, represent real-world entities, and organize your code in a logical and accessible manner.
In JavaScript, an object is a standalone entity characterized by a collection of properties and methods. Through this lesson, you will learn how to create, manipulate, and utilize these objects, enhancing your ability to write more effective code. Whether you are storing user data, configuring settings, or representing complex systems, mastering JavaScript objects is a crucial step in your development as a JavaScript programmer.
This lesson is a comprehensive overview, and in the following lessons in this section, you'll get to look at each aspect of objects individually.
What is a JavaScript Object?
In JavaScript, an object is a fundamental data structure that's used to store collections of data and more complex entities. Defined as an unordered collection of related data, in the form of “key: value” pairs, JavaScript objects offer a flexible way to organize and access data.
Each key in an object acts like a variable name that's linked to a value, which can be of any JavaScript data type, including numbers, strings, arrays, functions, and even other objects. This structure makes objects incredibly versatile for various tasks, such as storing configurations, modeling real-world scenarios, or managing application state.
Objects in JavaScript are mutable, meaning they can be modified after their creation, allowing for dynamic and interactive programming. Embracing the power of objects is essential for any JavaScript developer, as they provide a robust framework for building complex and functional code structures. This is one of the most important data structures that you will learn!
One of JavaScript's most intriguing and powerful aspects is the way almost everything can be treated as an object. This includes arrays and functions and even primitive data types such as numbers and strings. Underneath the hood, JavaScript treats these entities as objects, providing them with methods and properties that enable rich interaction and manipulation.
For instance, a string in JavaScript may be considered as an array of characters, offering methods for string manipulation. Functions, too, are objects, equipped with properties and capable of being passed around as values. This object-centric approach grants JavaScript its characteristic flexibility and dynamism, allowing developers to approach problem-solving in a versatile and intuitive manner.
Accessing Values in JavaScript Objects: Dot Notation and Bracket Notation
In JavaScript, objects store their data in key-value pairs, and accessing these values is a fundamental aspect of working with objects. There are two primary ways to reference values from an object: dot notation and bracket notation.
Dot Notation
Dot notation is the most common and straightforward way to access the value of a property from an object. With this method, you use a dot followed by the property name (key) to access its value. For example:
// Accessing properties using dot notation
Math.PI
// 3.141592653589793
In this example, you accessed a global object that is pre-included in the typical browser JavaScript environment. It has a bunch of utility values, and the value of pi (π) is among them.
Dot notation is concise and easy to read, making it a popular choice for accessing properties. However, it has a limitation: the property name must be a valid JavaScript identifier; it cannot start with a number, contain spaces or special characters other than $ and _).
Bracket Notation
Bracket notation provides more flexibility than dot notation. It allows you to access properties using a string, which can include variables, numbers, or characters that aren't valid identifiers. This method uses square brackets with the property name (as a string) inside them. For instance:
Math["PI"]
// 3.141592653589793
Bracket notation is essential when dealing with dynamic property names or when property names are not valid identifiers. It's also the only way to access a property name that is stored in a variable:
let propName = "PI";
console.log(Math[propName]); // 3.141592653589793
Choosing Between Dot and Bracket Notation
While dot notation is more succinct and is often preferred for its readability, bracket notation offers greater flexibility. The choice between them depends on the context:
- Use dot notation when you know the fixed, valid identifier property name.
- Use bracket notation when dealing with variable property names, or when property names include special characters or start with digits.
If you try to access a property of an object that doesn't exist on that object, the return value will be the undefined primitive type:
let value = Math.PIES
console.log(value); // undefined
It won't throw an error if the object itself exists.
Now that you know how to reference object properties, it's time to move on to creating objects from scratch.
How to Create an Object
There are a few ways to create an object in JavaScript, but you'll typically only ever use object literal notation. For example, to create a new and empty object, all you need to do is to type a pair of curly braces {}, which are sometimes called curly brackets:
let thing = {};
console.log(thing); // {}
This literal annotation creates a variable and assigns the object to it. You've created your first object!
In JavaScript, apart from the object literal notation, you can create an empty object using the Object constructor function. This is done by calling new Object(), which creates and returns a new object. Here's an example demonstrating this:
let thing = new Object();
console.log(thing); // {}
In this case, thing is an empty object created using the Object constructor. This method is less common compared to the object literal notation for creating empty objects, as it's more verbose. However, it's equally valid and can be useful in certain situations, especially when creating objects dynamically or when working with more complex object-oriented programming concepts.
When you assign an object to a variable in JavaScript, it's important to understand that you are assigning a reference to that object, not the actual object itself. This contrasts with primitive value assignment (like numbers, strings, or booleans), where the actual value is assigned to the variable.
When you assign an object to a variable, you're essentially assigning a pointer to the memory location where that object is stored. This means if you assign this object to another variable and then modify the object through one of the variables, the change will be reflected when accessed via both variables. For example:
let obj1 = { value: 10 };
let obj2 = obj1;
obj2.value = 20;
console.log(obj1.value); // 20
Here, obj2 is not a new, independent object; it's a reference to the same object as obj1. This reference characteristic leads to behavior that might be unexpected if you're thinking of objects as you do primitive values. It's a fundamental concept in JavaScript that plays a significant role in understanding how data is stored, passed, and manipulated within your programs.
Note that arrays are also assigned by reference!
Typically, you won't just create an empty object, but you'll want to initialize it with certain values. Creating an object initialized with values using object literal notation in JavaScript is straightforward and intuitive. You define the object and its properties (key-value pairs) within curly braces {}. Here's an example:
let person = {
name: "Nomad",
age: 30,
occupation: "Engineer"
};
In this example, person is an object with three properties:
namewith the value"Nomad",agewith the value30,occupationwith the value"Engineer".
Each property is defined as a key-value pair, with the key (like name) and its associated value ("Nomad"), separated by a colon :. This method of creating objects is the most common in JavaScript due to its simplicity and readability.
How to Change an Object: Adding and Removing Properties
JavaScript's dynamic nature allows for the flexible manipulation of objects, including the ability to add or remove properties on the fly. This flexibility is a powerful feature of the language, enabling developers to adapt objects according to the needs of their programs.
Adding Properties to an Object
To add a new property to an existing object, you reference a new key and assign a value to it. If the key does not exist on the object, JavaScript will automatically create it. For example:
let car = {
make: 'Fiat',
model: 'Panda'
};
// Adding some new properties
car.year = 2010;
car['color'] = 'white';
console.log(car); // { make: 'Fiat', model: 'Panda', year: 2010, color: 'white' }
console.log(car.color); // "white"
console.log(car["year"]); // 2010
In this example, two new properties, year and color, are added to the car object using both dot notation and bracket notation. You can use both types of notation to reference values from an object or assign values to an object.
Removing Properties from an Object
To remove a property from an object, the delete operator is used. This operator removes a property from an object if it exists. After deletion, trying to access that property will return undefined. Here's how it works:
let car = {
make: 'Fiat',
model: 'Panda'
};
delete car.model;
console.log(car); // { make: 'Fiat' }
In this case, the model property is removed from the car object.
While adding and removing properties are straightforward in JavaScript, it's essential to use these capabilities judiciously. Excessive dynamic changes to objects can lead to code that is difficult to read and maintain. It's often better to structure objects upfront with all necessary properties, even if some of them might initially be set to null or undefined.
This ability to dynamically alter objects makes JavaScript particularly flexible and powerful, but it also places a responsibility on developers to manage objects thoughtfully to maintain code clarity and integrity.
JavaScript Object Notation and Some Examples of Common Object Shapes
JavaScript Object Notation, commonly known as JSON, is a format that has transcended its origins in JavaScript to become a cornerstone of data exchange on the internet. Its structure, based on key-value pairs, is both simple and highly versatile, making it an ideal format for representing structured data in a readable and easily transferable form. JSON's popularity is evident in its widespread use across various programming languages and platforms, not just in JavaScript.
JSON files, which you might encounter quite often, are essentially text files formatted to mimic the structure of JavaScript objects. These files use the same key-value pairing to store data. You'll dive deeper into JSON in a later lesson, but for now, focus on familiarizing yourself with the shape of some JavaScript objects which are commonly seen in JSON files.
Consider the following examples of typical JavaScript objects:
let languages = {
javascript: 'loosely typed',
typescript: 'strongly typed'
};
let student = {
age: 100,
willingToLearn: true,
motto: "If at first you don't succeed, try, try again."
};
let temperatures = [
{ scale: "Celsius", temp: 35, location: "Barcelona" },
{ scale: "Fahrenheit", temp: 20, location: "Wichita" },
{ scale: "Celsius", temp: 2, location: "Moscow" },
{ scale: "Fahrenheit", temp: 35, location: "Boston" },
{ scale: "Fahrenheit", temp: 67, location: "Kiev" },
{ scale: "Celsius", temp: 12, location: "Glasgow" }
];
In these examples, languages and student are simple objects, with keys like javascript and age, and corresponding values like 'loosely typed' and 100. The temperatures example illustrates an array of objects, each object representing a temperature record with attributes like scale, temp, and location.
Notice how in the temperatures example, each element within the array is an object, effectively showcasing how objects can nest within other structures, such as arrays, to represent more complex data sets. All of these examples are valid JSON.
As an exercise, try creating your own student object with details relevant to you. Add properties that reflect your interests or academic focus. Once you've created your object, experiment by logging it to the console in your browser's developer tools. This practice will not only solidify your understanding of JavaScript objects but also give you a glimpse into how data is structured and manipulated in real-world applications.
JavaScript Objects and the Hash Table
JavaScript objects are often compared to hash tables, a fundamental data structure used in computer science. A hash table stores key-value pairs and provides fast data retrieval based on the key. Similarly, a JavaScript object organizes data in key-value pairs, where the keys are strings (or symbols) and the values can be of any data type.
The resemblance to hash tables lies in the efficiency of accessing data. In a hash table, a hash function computes the index for a key, enabling quick data retrieval, regardless of the size of the data set. Retrieving data has O(1) time complexity. JavaScript objects work similarly, allowing you to quickly access a property's value using its key.
It's important to note that JavaScript objects do not guarantee the order of properties, unlike arrays. Objects are unordered. This is because the underlying implementation, resembling a hash table, focuses on speed and efficiency of access rather than maintaining order. When the order of elements is crucial, arrays or new data structures like Map should be used.
JavaScript objects' similarity to hash tables thus provides a powerful and efficient way to handle structured data, with the caveat that they are inherently unordered collections.
Summary: Introduction to JavaScript Objects
- JavaScript objects are crucial in the language for creating complex structures, embodying mutable key-value pairs for dynamic programming.
- Treating almost everything as an object, including arrays and functions, JavaScript enables methods and property manipulation for various data types.
- Object properties can be accessed through dot notation for straightforward cases and bracket notation for dynamic or special character names.
- Objects are primarily created using object literal notation
{}or theObjectconstructornew Object(), with literals being more common. - Dynamic object manipulation involves adding new properties directly or removing them using the
deleteoperator, demanding careful code management. - JavaScript objects resemble hash tables in their key-value pair storage and efficient data access, but are unordered, unlike arrays.