====== JS: Methods ====== ===== Array Methods ===== ==== .forEach() ==== ''.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

paragraph.textContent = fruit; //

text content = fruit container.appendChild(paragraph); // append

into container }); // --------------------------------------- // BONUS: TEMPLATE LITERALS APPROACH ----- // --------------------------------------- container.innerHTML = fruits .map(fruit => `

${fruit}

`) // Transform array into HTML strings .join(""); // Join them into one big text block
==== .map() ==== Creates a NEW array by transforming every element in an array. ==== .filter() ==== Creates a NEW array with only the elements that pass a test. ==== .find() ==== Returns a single item that matches a rule. ==== .includes() ==== Returns true/false. A simple check to see if an array contains a value. ==== .reduce() ==== Takes a list of items and reduces them down to a single value. ==== .some() ==== Returns true/false. Checks if at least one item in the array passes a test. ==== .every() ==== Returns true/false. Checks if all items in the array pass a test. ==== .sort() ==== Does NOT create a new array. Sorts the existing array. ==== .slice(start, end) ==== The “safe” one. Copies a chunk of the array and returns it. Does NOT change the original array. ==== .splice(start, count) ==== The “destructive” one. Goes into the array and removes items from the original. ===== String Methods ===== ==== .split() ==== 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"] ==== .join() ==== Glues an array back into a string. (opposite of ''.split()'') const slug = ["my", "cool", "post"].join("-"); // "my-cool-post" ==== .trim() ==== Removes whitespace from the start and end of a string. const email = " user@email.com "; console.log(email.trim()); // "user@email.com" ==== .includes() ==== 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