Skip to content

Workshop on JavaScript objects, loops, and files

Part 1: Practical

The practical part of today’s workshop is mostly in one file, “shapes.js”. Download it to get started.

There are some optional steps at the end that also require two other files: “extraColors.js” and “package.json”. Download both files or copy-paste into your own versions to get started. Then follow the instructions in “shapes.js”.

Download shapes.js

js
// shapes.js
// Workshop on objects and loops

// 1. Make an array called 'shapes' containing strings that are the names of
// shapes. It should have at least three shapes.


// 2. Log the third item in the array to the console, without retyping the
// name of the shape.


// 3. Add another shape to the array


// 4. Write a loop that goes through all the shapes in the array.
// In the loop, log each shape to the console.
// Also log the second letter in each shape.


// 5. Choose three colors. Get the hex code for each one, and pick a name for each one.
// Make an object called 'colors' that has a property for each color.
// Use the color name as the key, and the hex code as the value.


// 6. Log the hex code of one of your colors to the console, without retyping the
// code.


// 7. Write a loop that goes through the colors. For each one, log a sentence to
// the console that says "I have a green triangle with code #000000" but
// substituting the particular color name and code each time.


// 8. Write a loop that goes through the colors. For each one, transform the
// hex code to lowercase letters, changing the property values as you go.
// Then log the colors object.
// Hint: Not sure if it's working? Make sure there's at least one uppercase letter in
// the object definition above, and check that it's lowercase when logged.


// 9. Write a loop that goes through the shapes. Inside the shape loop, write
// another loop that goes through the colors. Inside the color loop, log the
// sentence "You have a red rectangle" but substitute the shape AND the color
// every time.


// 10. Modify the above code so that it only logs the sentence if the hex code
// contains the letter 'e'.

// 11. Build an array called 'hexCodes' listing just the hex codes. To build
// it, please use a for loop that goes over your colors object, rather than
// retyping the codes. Then log the array to the console.

// 11b. OPTIONAL
// The next two steps involve exporting and importing with a pattern from ES
// modules. We did not cover all the steps in class, so they are optional.
// Make sure you've downloaded the file package.json and saved it in the same
// folder as this one.
// Here is a one minute video demo of "type":"module" in package.json:
// https://www.youtube.com/watch?v=I4gR-1qMjk0

// 12. OPTIONAL
// Make sure you've downloaded the file extraColors.js and saved
// it in the same folder as this one. Modify the line where the pinkAndYellow
// object is defined, so that it is exported. Then import it below, in this
// file, and log it to the console.


// 13. OPTIONAL
// Write a loop that goes through pinkAndYellow. Inside the loop, add each
// new color to your colors object. Log the updated colors object to the console.


// 14. OPTIONAL CHALLENGE Use more loops to build an object called
// 'charFrequencies' that
// records each character that appears in the hex codes, and how many times
// each one appears, overall. Each key should be a character, and each value
// should be the number of times that character appears. Then log it to the console.
// For example, at the end of your looping, your object might look like this:
// charFrequencies = {
//   'e': 5,
//   '6': 1,
//   ...
// }
// Hint 1. For each character, the action to take will vary, depending on
// whether you've already added that character to the object. Try using an if
// statement to handle this.
// Hint 2. You may need to use the built-in hasOwnProperty() method of the object.
// Hint 3. Try excluding the hash (#) from charFrequencies.
// shapes.js
// Workshop on objects and loops

// 1. Make an array called 'shapes' containing strings that are the names of
// shapes. It should have at least three shapes.


// 2. Log the third item in the array to the console, without retyping the
// name of the shape.


// 3. Add another shape to the array


// 4. Write a loop that goes through all the shapes in the array.
// In the loop, log each shape to the console.
// Also log the second letter in each shape.


// 5. Choose three colors. Get the hex code for each one, and pick a name for each one.
// Make an object called 'colors' that has a property for each color.
// Use the color name as the key, and the hex code as the value.


// 6. Log the hex code of one of your colors to the console, without retyping the
// code.


// 7. Write a loop that goes through the colors. For each one, log a sentence to
// the console that says "I have a green triangle with code #000000" but
// substituting the particular color name and code each time.


// 8. Write a loop that goes through the colors. For each one, transform the
// hex code to lowercase letters, changing the property values as you go.
// Then log the colors object.
// Hint: Not sure if it's working? Make sure there's at least one uppercase letter in
// the object definition above, and check that it's lowercase when logged.


// 9. Write a loop that goes through the shapes. Inside the shape loop, write
// another loop that goes through the colors. Inside the color loop, log the
// sentence "You have a red rectangle" but substitute the shape AND the color
// every time.


// 10. Modify the above code so that it only logs the sentence if the hex code
// contains the letter 'e'.

// 11. Build an array called 'hexCodes' listing just the hex codes. To build
// it, please use a for loop that goes over your colors object, rather than
// retyping the codes. Then log the array to the console.

// 11b. OPTIONAL
// The next two steps involve exporting and importing with a pattern from ES
// modules. We did not cover all the steps in class, so they are optional.
// Make sure you've downloaded the file package.json and saved it in the same
// folder as this one.
// Here is a one minute video demo of "type":"module" in package.json:
// https://www.youtube.com/watch?v=I4gR-1qMjk0

// 12. OPTIONAL
// Make sure you've downloaded the file extraColors.js and saved
// it in the same folder as this one. Modify the line where the pinkAndYellow
// object is defined, so that it is exported. Then import it below, in this
// file, and log it to the console.


// 13. OPTIONAL
// Write a loop that goes through pinkAndYellow. Inside the loop, add each
// new color to your colors object. Log the updated colors object to the console.


// 14. OPTIONAL CHALLENGE Use more loops to build an object called
// 'charFrequencies' that
// records each character that appears in the hex codes, and how many times
// each one appears, overall. Each key should be a character, and each value
// should be the number of times that character appears. Then log it to the console.
// For example, at the end of your looping, your object might look like this:
// charFrequencies = {
//   'e': 5,
//   '6': 1,
//   ...
// }
// Hint 1. For each character, the action to take will vary, depending on
// whether you've already added that character to the object. Try using an if
// statement to handle this.
// Hint 2. You may need to use the built-in hasOwnProperty() method of the object.
// Hint 3. Try excluding the hash (#) from charFrequencies.

Download extraColors.js

js
const pinkAndYellow = {
  extraPink: '#d703fc',
  extraYellow: '#fcf803',
}
const pinkAndYellow = {
  extraPink: '#d703fc',
  extraYellow: '#fcf803',
}

Download package.json

json
{
  "type": "module"
}
{
  "type": "module"
}

Part 2: Creative

Choose one of the three options below.

Creative option A: Make something!

Scenario: Choose something that you can represent in code with arrays and objects. It can be info about some of your favorite songs, TV shows, clothes, hobbies, pets, work, etc.

Goal: Write a program including arrays, objects, and loops that uses that info to tell a story or investigate the answer to some questions about the info.

Creative option B: Explore 1980s hit song data

Scenario

You are a developer working on a music streaming app. You use JavaScript to work with data about songs, albums, artists, and audio generally. You’ve been provided with a list of top singles from the UK in the 1980s (see starter files below).

Goal

Ask some questions that the data can answer, using loops. Can’t think of any? Try these.

  1. What’s the longest song title (in terms of number of characters)?
  2. What’s the shortest title?
  3. Is “I” or “You” used more often? How about “Me”? How about “Love”?
  4. What was the top ranked song for each year?
  5. Which artist appears on the list most often?
  6. Can you use a for loop to write an HTML document (a string) with markup for a ul and li items, using the data?

Starter code

Download songData.js (too long to show here)

Download songs.js

js
// songs.js
import { songs } from './songData.js'

// console.log(songs)
// songs.js
import { songs } from './songData.js'

// console.log(songs)

Creative option C: Image factory (warning: challenging!)

Scenario

You are a developer working on a web app where users can choose a color and download geometric shapes in that color. The shapes are made with SVG (scalable vector graphics), which is a markup language that can be used to encode graphics like logos, icons, and illustrations.

Objective

In the starter code below, you are given a square, encoded using SVG markup. Create at least five copies of the square in different colors, and save them all as files in the folder called “output”.

Starter code

Download images.js

js
// images.js
// This line imports some built-in Node helper functions
import { accessSync, mkdirSync, writeFileSync } from "node:fs"

// This creates a subfolder called 'output' if it doesn't already exist
try {
  accessSync('output')
} catch (err) {
  mkdirSync('output')
}

// Here are a few geometric shapes for you to work with.
// They are encoded using SVG markup (Scalable Vector Graphics),
// which is used for icons, logos, and illustrations.
// Keep in mind, within this JavaScript file, they are just
// strings, so you can treat them as strings.
const square = `<?xml version="1.0" encoding="UTF-8"?>
                <svg id="square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160">
                  <defs><style>.cls-1{fill:#e94c33;}</style></defs>
                  <rect class="cls-1" width="160" height="160"/>
                </svg>`

const triangle = `<?xml version="1.0" encoding="UTF-8"?>
                  <svg id="triangle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 73.5 63.65">
                    <defs><style>.cls-1{fill:#ec8323;}</style></defs>
                    <polygon class="cls-1" points="36.75 63.65 0 0 73.5 0 36.75 63.65"/>
                  </svg>`

const circle = `<?xml version="1.0" encoding="UTF-8"?>
                <svg id="circle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 61.74 61.74">
                  <defs><style>.cls-1{fill:#1579A0;}</style></defs>
                  <path class="cls-1" d="m0,30.87c0,17.05,13.82,30.87,30.87,30.87s30.87-13.82,30.87-30.87S47.92,0,30.87,0,0,13.82,0,30.87"/>
                </svg>`
// images.js
// This line imports some built-in Node helper functions
import { accessSync, mkdirSync, writeFileSync } from "node:fs"

// This creates a subfolder called 'output' if it doesn't already exist
try {
  accessSync('output')
} catch (err) {
  mkdirSync('output')
}

// Here are a few geometric shapes for you to work with.
// They are encoded using SVG markup (Scalable Vector Graphics),
// which is used for icons, logos, and illustrations.
// Keep in mind, within this JavaScript file, they are just
// strings, so you can treat them as strings.
const square = `<?xml version="1.0" encoding="UTF-8"?>
                <svg id="square" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160">
                  <defs><style>.cls-1{fill:#e94c33;}</style></defs>
                  <rect class="cls-1" width="160" height="160"/>
                </svg>`

const triangle = `<?xml version="1.0" encoding="UTF-8"?>
                  <svg id="triangle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 73.5 63.65">
                    <defs><style>.cls-1{fill:#ec8323;}</style></defs>
                    <polygon class="cls-1" points="36.75 63.65 0 0 73.5 0 36.75 63.65"/>
                  </svg>`

const circle = `<?xml version="1.0" encoding="UTF-8"?>
                <svg id="circle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 61.74 61.74">
                  <defs><style>.cls-1{fill:#1579A0;}</style></defs>
                  <path class="cls-1" d="m0,30.87c0,17.05,13.82,30.87,30.87,30.87s30.87-13.82,30.87-30.87S47.92,0,30.87,0,0,13.82,0,30.87"/>
                </svg>`

Clues and tips

  • Program structure: First create an array with all the color codes you want, or an object with color names and color codes as key-value pairs. Then you can iterate over this with a for loop to create one copy of the image for each color.

  • SVG format: Don’t worry if you haven’t used SVG markup before--you already know some of it, because it’s similar to HTML and CSS in many ways. Look for familiar patterns. Can you tell where the color is defined in the code?

  • Changing the colors: Once you have found the color definition in the SVG code, you’ll want to change it. Try looking up how the replace() method works on strings.

  • Saving each file: You’ll need the built-in function called writeFileSync(), which is already imported for you on line 1. It is used like this: writeFileSync('output-folder-name/file-name.txt', 'content of file as a string'). Note: on Windows, you have to use backslash (\) between the folder name and file name, and on Mac and Linux, you have to use forward slash (/).

Content CC BY 4.0 | Code AGPL 3.0