JavaScript and TypeScript course Β· Module 5: Advanced JavaScript
Objects and Arrays in JavaScript
In this lesson5
In Jurassic Park we store enormous amounts of data about dinosaurs - their names, species, age, health status, and much more. Imagine keeping every piece of information in a separate variable: blueName, blueAge, blueSpecies, and then the same again for Charlie and Delta. Within a week the lab is drowning in unlabeled test tubes. To manage this data efficiently, we need two fundamental JavaScript data structures: objects and arrays.
What You Will Learn
- package a dinosaur's data into an object, its DNA card
- read, change and delete properties
- add methods, that is behaviors, to the card
- build and nest arrays
- recognize patterns: from a literal to a class
Objects - Dinosaur DNA Cards
An object in JavaScript is a collection of key-value pairs that lets you store related data in one place. Think of an object as a dinosaur information card - it contains all the relevant data in an organized way.
Creating Objects
The simplest way to create an object is with curly braces {}, known as an object literal. Inside, you write pairs: a key, a colon and a value, separated by commas:
1// Velociraptor information card
2const raptor = {
3 name: "Blue",
4 species: "Velociraptor",
5 age: 4,
6 isAlpha: true,
7 dangerLevel: 8
8};
9
10console.log(raptor); // Displays the entire objectBlue's whole card is now one value in one constant. The new Object() syntax also exists, but the literal is shorter and it is the standard. Don't mix up the brackets: curly braces {} create an object, square brackets [] create an array.
Accessing Object Properties
There are two ways to access an object's properties: dot notation and bracket notation, where you pass the key name as a string:
1// 1. Dot notation - most commonly used
2console.log(raptor.name); // "Blue"
3console.log(raptor.age); // 4
4
5// 2. Bracket notation - useful for dynamic keys
6console.log(raptor["species"]); // "Velociraptor"
7
8const property = "dangerLevel";
9console.log(raptor[property]); // 8 - useful when the key is in a variableBoth routes lead to the same value. I recommend the dot for everyday use and keeping brackets for keys stored in a variable. The raptor->name syntax known from other languages is a syntax error here, and reading a missing key simply returns undefined.
Modifying and Adding Properties
A dinosaur card is not carved in stone: age goes up, a raptor moves to another enclosure, and some entries need to be crossed out. An assignment or the delete operator is all it takes:
1// Modifying an existing property
2raptor.age = 5;
3
4// Adding a new property
5raptor.habitat = "Enclosure A3";
6
7// Deleting a property
8delete raptor.habitat;Assigning to an existing key overwrites the value, assigning to a new key adds a property, and delete removes it completely. What did not change? raptor still points to the same object - const only forbids reassigning the constant, not changes inside it.
Object Methods
An object can contain functions as values - we call these methods. They are the dinosaur's behaviors, stored right next to its data:
1const raptor = {
2 name: "Blue",
3 age: 4,
4 isAlpha: true,
5 skills: ["hunt", "communicate", "lead"],
6
7 // Method - a function inside an object
8 attack() {
9 return this.name + " attacks!";
10 },
11
12 // Another method using this
13 introduce() {
14 return "I am " + this.name + ", I am " + this.age + " years old.";
15 }
16};
17
18console.log(raptor.attack()); // "Blue attacks!"
19console.log(raptor.introduce()); // "I am Blue, I am 4 years old."Inside a method, this points to the object the method was called on, which is why raptor.attack() knows Blue's name without any argument. The skills property also shows that a value can be a whole array.
Three Ways to Write a Method
You can write a method in three ways, and all of them are valid JavaScript. Let's compare them on a single card:
1const raptor = {
2 name: "Blue",
3 // 1. Method shorthand (ES6)
4 hunt() { return this.name + " is hunting"; },
5 // 2. Property holding a function expression
6 communicate: function () { return this.name + " is communicating"; },
7 // 3. Property holding an arrow function
8 roar: () => "Rawr!"
9};
10
11console.log(raptor.hunt()); // "Blue is hunting"
12console.log(raptor.communicate()); // "Blue is communicating"
13console.log(raptor.roar()); // "Rawr!"The first two forms behave identically. An arrow function has no this of its own, though, so this.name inside it will not point to the raptor. I recommend the shorthand: it is the shortest, and this behaves predictably in it.
Static Object Methods
JavaScript provides several useful methods for working with objects. You call them on the global Object and pass the card as an argument:
1const dino = { name: "Rex", species: "T-Rex", age: 12 };
2
3// Object.keys() - array of keys
4console.log(Object.keys(dino)); // ["name", "species", "age"]
5
6// Object.values() - array of values
7console.log(Object.values(dino)); // ["Rex", "T-Rex", 12]
8
9// Object.entries() - array of [key, value] pairs
10console.log(Object.entries(dino));
11// [["name", "Rex"], ["species", "T-Rex"], ["age", 12]]Each of them returns a new array, and the dino object stays untouched. Keys help you check which fields a card has, and the pairs from Object.entries() let you loop over keys and values at once.
Arrays - Dinosaur Lists
An array is an ordered list of elements, ideal for storing collections of data of the same type.
Creating Arrays
You create an array with square brackets [], separating the elements with commas. Every element has a position number, its index, counted from zero:
1// Array of Velociraptor names
2const raptors = ["Blue", "Charlie", "Delta", "Echo"];
3
4// Array of objects
5const dinosaurs = [
6 { name: "Blue", species: "Velociraptor", age: 4 },
7 { name: "Rex", species: "T-Rex", age: 12 },
8 { name: "Bronto", species: "Brachiosaurus", age: 8 }
9];
10
11console.log(raptors[0]); // "Blue" - first element (index 0)
12console.log(raptors.length); // 4 - number of elements
13console.log(dinosaurs[1].name); // "Rex" - accessing an object in the arraySo the last of four raptors has index 3, which is length - 1. Reading outside the range, for example raptors[10], returns undefined instead of an error. You reach the fields of an object stored in an array by combining the index with a dot.
Complex Data Structures
Objects and arrays can be nested to create complex data structures - the park map contains sectors, and each sector has a list of residents:
1const park = {
2 name: "Jurassic Park",
3 sectors: [
4 {
5 id: "A",
6 name: "Predator Zone",
7 dinosaurs: ["T-Rex", "Velociraptor"]
8 },
9 {
10 id: "B",
11 name: "Herbivore Zone",
12 dinosaurs: ["Brachiosaurus", "Triceratops"]
13 }
14 ]
15};
16
17console.log(park.sectors[0].dinosaurs[1]); // "Velociraptor"You read the path park.sectors[0].dinosaurs[1] from the left: the park, the first sector, its list, the second element. Every step is just a dot or just an index.
From Card to Factory - Object Patterns
As the raptors multiply, rewriting a card for each of them quickly gets tiring. The patterns climb like stairs: a plain object, an object with methods, a factory function, a constructor function and a class. A factory function returns a new object every time you call it:
1function createRaptor(name, age) {
2 return {
3 name,
4 age,
5 attack() {
6 return this.name + " attacks!";
7 }
8 };
9}
10
11const charlie = createRaptor("Charlie", 3);
12console.log(charlie.attack()); // "Charlie attacks!"Writing name, is shorthand for name: name. Higher up the stairs stand the constructor function called with new, whose methods live on a shared prototype, and the class - a more modern syntax for the same mechanism. You know classes from the location about ES6 class syntax, and here they come back in the Builder pattern.
Array or Object?
Choosing a structure starts with analyzing the data: will you look things up by order or by name? A herd you go through one by one is an array, while a description of one animal with named traits is an object. Then you implement and test, and leave optimization for the end.
In the lab below, Blue's card and an empty park map are waiting - fill in the sectors following the TODO comments. In the next lesson you will start managing the herd with array methods such as push() and splice().
Remember: an object is the DNA card of one dinosaur, and an array is the list of the whole herd.
Code for this lesson: index.js
1// Objects and arrays in Jurassic Park
2
3// === OBJECTS ===
4// Create an object raptor with the properties: name, species, age, isAlpha, skills (array)
5const raptor = {
6 name: "Blue",
7 age: 4,
8 isAlpha: true,
9 skills: ["hunt", "communicate", "lead"],
10
11 // Add a method attack() that returns: this.name + " attacks!"
12 attack() {
13 return this.name + " attacks!";
14 }
15};
16
17console.log("=== The raptor object ===");
18console.log("Name:", raptor.name);
19console.log("Age:", raptor.age);
20console.log("Attack:", raptor.attack());
21console.log("First skill:", raptor.skills[0]);
22
23// Object methods
24console.log("\n=== Object methods ===");
25console.log("Keys:", Object.keys(raptor));
26console.log("Values:", Object.values(raptor));
27
28// === ARRAYS ===
29const raptors = ["Blue", "Charlie", "Delta", "Echo"];
30console.log("\n=== Array raptors ===");
31console.log("Pack:", raptors);
32console.log("First:", raptors[0]);
33console.log("Length:", raptors.length);
34
35// === COMPLEX STRUCTURES ===
36// TODO: Create an object park with a property sectors (an array of objects)
37// Each sector should have: id, name, dinosaurs (array)
38const park = {
39 name: "Jurassic Park",
40 sectors: [
41 // TODO: Add sectors
42 ]
43};
44
45console.log("\n=== Park ===");
46console.log(park);Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which of the following is a valid syntax for creating an object in JavaScript?
2. Which of the following ways to access an object property are valid?
These are 2 of 5 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create: const raptor = { name: 'Blue', age: 4, isAlpha: true, skills: ['hunt', 'communicate', 'lead'], attack() { return this.name + ' attacks!' } }. Call raptor.attack() and raptor.skills[0].