← Learn Javascript

Data Structures

How to use Javascript arrays, objects, and loops

slides | md

Introduction

Review the following sections and perform the activities on your own or with your group.

Perform the task(s) when you see this πŸ‘‰ emoji

Learning Objectives

Students who complete this module will be able to:

  • Explain the difference between arrays and objects
  • Demonstrate how to loop through an array to display its values in HTML
  • Create a Javascript object to represent some real life entity
Homework

Data collections

In addition to primitive data types, Javascript can store collections of data like arrays and objects, as well as more complex entities.

true

Arrays

  • A Javascript array is a data type that can store multiple values.
  • Create an array using a variable declaration, a name, and multiple comma-separated values between square brackets.
  • To get an array value, use the index, the position or order of the data in the array, between two square brackets.
let colors = ["purple", "green", "blue"]; // array of strings
colors[0]; // -> "purple"
πŸ‘‰ Try these blocks of code in the console.

Array indexes

  • Arrays are zero-indexed, with the first value is stored at index 0, then 1, and so on.
  • While indexes start at zero, their length reflects the total indexes in the array.
  • Like variables, you can also set values using the index.
colors.length; // -> 3
colors[0] = "red"; // set the value of the first index
colors[0]; // -> "red"

Array methods

Like other Javascript types, the console can list properties and methods specific to arrays.

πŸ‘‰ Try it out - Run these in the console

[] // the array constructor
// how many indexes?
["abc", 123].length
// create array, confirm length
let colors = ["red", "green", "blue"]
// what is the index of "green"?
colors.indexOf("green")
// what will this return?
colors.slice(1,3)
Solution
["abc", 123].length // -> 2
colors.indexOf("green") // -> 1
colors.slice(1,3) // -> ["green", "blue"]

Loops

  • One of the benefits to working with arrays is that you can write code that automatically repeats some task for each index.
  • All languages have loop statements which practically do the same thing: repeat a block of code based on some condition.

Loop anatomy

The for loop in Javascript makes explicit the three essential components of a loop: 1) Create control variable 2) Test the condition 3) Iterate on each loop

for and while loops

Both the for and while loops do the same thing with a slightly different structure, running the code in the statement block until the condition is false.

// the three parts on one line
for (let i = 0; i < 10; i++){
	console.log(i);
}

let i = 0;
while (i < 10) {
	console.log(i);
	i++;
}

⚠️ Infinite loops

  • An infinite loop is a loop that never stops because it has no condition to exit.
  • This will cause your page to become unresponsive, crash the browser, or even freeze your computer.
  • This code example will crash your web page because the condition will never be false!
let i = 0;
while (true) {
	console.log(i++);
}

forEach loops

  • The Array type has a built-in Array.forEach function to loop through indexes.
  • It uses a callback that receives the item and index (below named i).
let colors = ["red", "green", "blue"]
// built-in array forEach
colors.forEach(function(item, i){
	console.log(i, item);
});

// -> 0 "red"
// -> 1 "green"
// -> 2 "blue"

While .forEach is syntactically simpler to write, one small issue is they are not easy to break from.

Multi-Dimensional Arrays

JS arrays can store the same or different data types, including other arrays.

πŸ‘‰ How would you loop through this array to output all individual values?

Solution

A loop inside a loop

// an array of arrays
const people = [
	['name', 'age', 'color'],
	['Mary', 18, 'mauve'],
	['Pam', 33, 'periwinkle'],
	['Chad', 81, 'chartreuse']
];
people[1][2] // -> 'mauve'

Looping through multi-dimensional arrays

An array inside an array adds a second dimension. Like a table, looping through a 2D array will need to not only go down a single column of indexes, but across each row as well.

// ... using array from previous slide
for (let i = 0; i < people.length; i++){
    // the 2nd loop uses a new iterator and condition
	for (let j = 0; j < people[i].length; j++){
        console.log(people[i][j]);
    }
}
// -> 'name'
// -> 'age'
// -> 'color' 
// -> ...

Multi-Dimensional Arrays

Arrays can also store objects and other complex types.

// array of date objects
const dates = [
	new Date(Date.UTC(1989, 10, 9, 17, 53, 0)), // UTC
	new Date("9 November 1989 18:53 UTC+1"), // BERLIN
	new Date("November 9, 1989 12:53 UTC-5") // NYC
];
dates[1].toUTCString()
// -> "Thu, 09 Nov 1989 17:53:00 GMT" (Berlin local time)

Objects

  • A Javascript object is another hierarchical format for storing collections.
  • While an array stores a list of values, data in objects is stored and retrieved using a key and dot notation.
const color = {
	"name": "red",
	"hex": "#ff0000",
	"rgb": [255,0,0]
}
console.log(color.name); // -> "red"
Use square brackets color['name'] to fetch a value if there is a special character or space in the key name.

Object Methods

Objects can even store functions. For example, these methods (a function stored in an object) of the built-in Date object:

πŸ‘‰ Try it out - Run these in the console

// expand object the constructor to see more methods
{}
// create instance of built-in Date() object
let d = new Date()
// The following methods are specific to the Date object
d.getFullYear()
// and show how objects can "encapsulate" their properties
d.toISOString()
// and methods to make them easier use.
d.valueOf()
Solution
// -> 2022
// -> '2022-10-29T12:00:04.566Z'
// -> 1667044804566

Date.toISOString converts to the ISO_8601 date format
Date.valueOf returns date and time as seconds since January 1, 1970 00:00:00 UTC

Encapsulation

  • Objects in arrays are handy because they encapsulate data, grouping like information inside a single container, and standardizing access.

var people = [
	{ name: "Joel", age: 99 },
	{ name: "John", age: 66 },
	{ name: "Jack", age: 33 }
];
people.forEach(function(item, i){
	console.log(`${item.name} is ${item.age} years old`);
});
// -> Joel is 99 years old
// -> John is 66 years old
// -> Jack is 33 years old

JSON

  • JSON (JavaScript object notation) is a serialized (saved as a string, not as memory) Javascript object that can be saved in / retrieved from .json files by your program.
  • Just like objects, you can store any* type in a JSON file, including arrays and other objects.
[
	{ "color":"red", "rgb": [255,0,0] },
	{ "color":"orange", "rgb": [255,165,0] },
	{ "color":"yellow", "rgb": [255,255,0] },
	{ "color":"green", "rgb": [0,255,0] },
	{ "color":"blue", "rgb": [0,0,255] },
	{ "color":"indigo", "rgb": [75,0,130] },
	{ "color":"violet", "rgb": [238,130,238] },
]
*Any type except methods

JSON Examples

  • Practically every mobile app you use is sending and receiving JSON data β€œbehind the scenes”.
  • Here are some examples from Tally Saves the Internet! hello, auth, game data, anonyname and I Know Where Your Cat Lives random cat, cat not found

Next steps

  1. Explore More Concepts at the end
  2. Try the Exercises below.
  3. Start working on homework listed in the schedule.
  4. Continue to the next lesson: jQuery slides | md

Exercises

πŸ‘‰ Try it out

  1. Lottery v.3 - Display all results within the HTML of the page
  2. Exercises from Eloquent Javascript
    1. Ch2 Looping a triangle, FizzBuzz, Chessboard
    2. CH4 The sum of a range, Reversing an array, A list, Deep comparison

References

More Concepts

Continue for more related concepts.

Objects

  • In addition to storing virtually any other datatype, custom objects can store methods ("functions") and reference internal data with the this keyword.
const ev = {
	name: "Fall of the Berlin Wall",
	link: "https://en.wikipedia.org/wiki/Fall_of_the_Berlin_Wall",
	date: new Date(Date.UTC(1989, 10, 9, 17, 53, 0)),
	timeZone: "CET",
	getLocalTimeStr: function(){
		return this.date.toLocaleString('de-DE', {timeZone: this.timeZone})
	}
};
console.log(`${ev.name}, ${ev.date.getUTCFullYear()}`);
// -> "Fall of the Berlin Wall, 1989"
console.log(ev.getLocalTimeStr()); // -> "9.11.1989, 18:53:00"

Presentation comments ...

// arrays are technically objects typeof([]) // -> 'object'