.forEach() Runs a function for each item. Does NOT return a new array.
// ------------------------ // FOR EACH APPROACH ------ // ------------------------ const fruits = ["apple", "banana", "cherry"]; // build array const container = document.getElementById("container"); // get container element fruits.forEach(fruit => { const paragraph = document.createElement("p"); // create <p> paragraph.textContent = fruit; // <p> text content = fruit container.appendChild(paragraph); // append <p> into container }); // --------------------------------------- // BONUS: TEMPLATE LITERALS APPROACH ----- // --------------------------------------- container.innerHTML = fruits .map(fruit => `<p>${fruit}</p>`) // Transform array into HTML strings .join(""); // Join them into one big text block
Creates a NEW array by transforming every element in an array.
Creates a NEW array with only the elements that pass a test.
Returns a single item that matches a rule.
Returns true/false. A simple check to see if an array contains a value.
Takes a list of items and reduces them down to a single value.
Returns true/false. Checks if at least one item in the array passes a test.
Returns true/false. Checks if all items in the array pass a test.
Does NOT create a new array. Sorts the existing array.
The “safe” one. Copies a chunk of the array and returns it. Does NOT change the original array.
The “destructive” one. Goes into the array and removes items from the original.
Chops a string into an array based on a separator character. Removes the separator character.
const sent = "hello-world-from-js"; const words = sent.split("-"); // ["hello", "world", "from", "js"]
Glues an array back into a string. (opposite of .split())
const slug = ["my", "cool", "post"].join("-"); // "my-cool-post"
Removes whitespace from the start and end of a string.
const email = " user@email.com "; console.log(email.trim()); // "user@email.com"
Checks if text exists inside a string. Note: it’s case-sensitive (Fox =/= fox).
const sentence = "The quick brown fox jumps over the dog."; // Check if the word "fox" exists in the sentence const hasFox = sentence.includes("fox"); console.log(hasFox); // true