Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active February 15, 2022 12:26
Show Gist options
  • Save acidtone/5c8b6c954dadb7f9e60cbb98cddc0230 to your computer and use it in GitHub Desktop.
Save acidtone/5c8b6c954dadb7f9e60cbb98cddc0230 to your computer and use it in GitHub Desktop.
JS Activity: Array.forEach() - Create a grammatically list of nouns

JS Activity: Array.forEach() - Create a comma-separated list of nouns

In this activity, you will generate a comma-separated list of nouns and display it on a web page.

For example, this array:

const nouns = [`one`, `two`, `three`];

Should be display on the page as a sentence in the following format:

One, Two and Three.

Instructions

  1. Create a function handleItem() that accepts the (JS-created) array item (the noun) as a parameter.
  2. Inside handleItem(), use .innerHTML and the addition assignment operator (+=) (or another method of your choice) to create a comma-separated of nouns so that:
    • the first character of each noun is capitalized;
    • each noun is separated by a comma;
    • the last noun is separated by the word and.
  3. Finally, using Array.forEach(): invoke handleItem() for each item in the noun array to create your comma-separated list.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>List of Items</title>
<link rel="stylesheet" href="main.css">
<script src="nouns-list.js" defer></script>
</head>
<body>
<h1>List of Items</h1>
<p class="nouns">[noun list here]</p>
</body>
</html>
const nouns = [
"bush",
"shovel",
"cave",
"mouth",
"shell",
"tear",
"razor",
"nest",
"pad",
"fear",
"prize",
"power",
"pocket",
"cane",
"pump",
"mask",
"junk",
"kiss",
"photo",
"shower",
"slide",
"freedom"
];
// 1. Create a function `handleItem()` that accepts the (JS-created) array `item` (the noun) as a parameter.
// 2. Inside `handleItem()`, use `.innerHTML` and the addition assignment operator (`+=`) (or another method of your choice) to create a comma-separated of nouns so that:
// - the first character of each noun is capitalized;
// - each noun is separated by a comma;
// - the last noun is separated by the word `and`.
// 3. Finally, using `Array.forEach()`: invoke `handleItem()` for each item in the noun array to create your comma-separated list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment