JavaScript Basics: Your First Programs
Arrays and Objects
In this lesson you will
- Create and change arrays
- Create objects and read their properties
- Combine arrays and objects to model real data
Introduction
So far each variable holds one value. Real programs handle many: a list of scores, a user with a name, an age and an email. JavaScript has two main tools for that: arrays and objects.
Arrays: ordered lists
An array holds values in order, inside square brackets. Each item has a position called an index, which starts at 0.
fruits[0] is the first item. length is the number of items.
Quick quiz
Which index is the first item of an array?
Changing arrays
pushadds to the end,popremoves from the end.includeschecks whether an item is there.jointurns an array into a string.
You can change what is inside a const array. What const protects is the variable itself, which cannot be pointed at a different array.
Objects: named properties
An object stores values under names, called properties, inside curly braces.
- Read a property with a dot,
person.name, or brackets,person["name"]. - Assign to change an existing property or add a new one.
Objects can hold functions
A function inside an object is called a method.
this inside a method refers to the object it belongs to. You will learn more about it in the advanced course.
Arrays of objects
The two combine into the shape of most real data: a list of things, each with properties.
Quick quiz
How do you read the name property of an object called person?
Try it yourself
Create an array of three objects, each with a title and year for your favourite films or books. Then loop over the array and print each one as a sentence.
Summary
- Arrays are ordered lists, starting at index 0. Use
push,pop,includesandjoin. - Objects hold named properties. Use dot or bracket notation.
- An array of objects is the most common data shape.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading