JavaScript Basics .b
110 flashcards · Programming Languages · by Mae000
Accessing the Last Array Element
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[fruits.length - 1];
One way to loop through an array, is using a for loop:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fLen = fruits.length; let text = "<ul>"; for (let i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; } text += "</ul>";
You can also use the Array.forEach() function:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = "<ul>"; fruits.forEach(myFunction); text += "</ul>"; function myFunction(value) { text += "<li>" + value + "</li>"; }
The easiest way to add a new element to an array is using the push() method:
const fruits = ["Banana", "Orange", "Apple"]; fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
const fruits = ["Banana", "Orange", "Apple"]; fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Adding elements with high indexes can create undefined "holes" in an array
const fruits = ["Banana", "Orange", "Apple"]; fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
In JavaScript, arrays always use numbered indexes.
const person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; person.length; // Will return 3 person[0]; // Will return "John"
JavaScript does not support arrays with named indexes.
const person = []; person["firstName"] = "John"; person["lastName"] = "Doe"; person["age"] = 46; person.length; // Will return 0 person[0]; // Will return undefined
The Difference Between Arrays and Objects
In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes.
When to Use Arrays. When to use Objects.
You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.
Create empty array
const points = new Array(); const points = [];
The new keyword can produce some unexpected results
// Create an array with 40 undefined elements: const points = new Array(40); // Create an array with one element: const points = [40];
How to Recognize an Array
typeof returns object To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray()
Another way to Recognize an Array
The instanceof operator returns true if an object is created by a given constructor: const fruits = ["Banana", "Orange", "Apple"]; fruits instanceof Array;
One method to convert an array to string
The JavaScript method toString() converts an array to a string of (comma separated) array values.
Another method to convert an array to string
The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator:
Popping method, Array
Popping items out of an array The pop() method removes the last element from an array:
Save a value that was popped out
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.pop();
Shifting elements
The shift() method removes the first array element and "shifts" all other elements to a lower index.
Save a value that was shifted
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.shift();
Add a new value using the length method
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi";
Delete array
Array elements can be deleted using the JavaScript operator delete. Using delete leaves undefined holes in the array. Use pop() or shift() instead.
Merging (Concatenating) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays
The concat() method does not change the existing arrays. It always returns a new array.
const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; const myChildren = myGirls.concat(myBoys);
The concat() method can take any number of array arguments:
const arr1 = ["Cecilie", "Lone"]; const arr2 = ["Emil", "Tobias", "Linus"]; const arr3 = ["Robin", "Morgan"]; const myChildren = arr1.concat(arr2, arr3);
The concat() method can also take strings as arguments:
const arr1 = ["Emil", "Tobias", "Linus"]; const myChildren = arr1.concat("Peter");
The splice() method can be used to add new items to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi");
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. The splice() method returns an array with the deleted items
you can use splice() to remove elements without leaving "holes" in the array
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1);
const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1);
The first parameter (0) defines the position where new elements should be added (spliced in). The second parameter (1) defines how many elements should be removed. The rest of the parameters are omitted. No new elements will be added.
JavaScript Array slice()
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(1);
Some slice method rules
The slice() method creates a new array. The slice() method does not remove any elements from the source array.
This example slices out a part of an array starting from array element 3 ("Apple"):
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(3);
The slice() method can take two arguments like slice(1, 3). The method then selects elements from the start argument, and up to (but not including) the end argument.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(1, 3);
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a primitive value is expected. This is always the case when you try to output an array.
Why are loops useful?
Loops are all about doing the same thing over and over again. Often, the code will be slightly different each time round the loop, or the same code will run but with different variables.
Looping through a collection: types
Array, set, Map
Looping through a collection: Why
Most of the time when you use a loop, you will have a collection of items and want to do something with every item.
The loop for an array
const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; for (const cat of cats) { console.log(cat); }
You can use map() to do something to each item in a collection and create a new collection containing the changed items.
function toUpper(string) { return string.toUpperCase(); } const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; const upperCats = cats.map(toUpper); console.log(upperCats); // [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
You can use filter() to test each item in a collection, and create a new collection containing only items that match:
function lCat(cat) { return cat.startsWith('L'); } const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; const filtered = cats.filter(lCat); console.log(filtered); // [ "Leopard", "Lion" ]
The filter method looks a lot like map(), except the function we pass in returns a boolean: if it returns true, then the item is included in the new array.
Note that map() and filter() are both often used with function expressions, Using function expressions we could rewrite the example above to be much more compact.
const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; const filtered = cats.filter((cat) => cat.startsWith('L')); console.log(filtered);
Basic for loop structure
for (initializer; condition; final-expression) { // code to run }
initializer
this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.
condition
this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
final-expression
this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true.
What a standard for loop loops like:
const results = document.querySelector('#results'); function calculate() { for (let i = 1; i < 10; i++) { const newResult = `${i} x ${i} = ${i * i}`; results.textContent += `${newResult}\n`; } results.textContent += '\nFinished!'; } const calculateBtn = document.querySelector('#calculate'); const clearBtn = document.querySelector('#clear'); calculateBtn.addEventListener('click', calculate); clearBtn.addEventListener('click', () => results.textContent = '');
Using for loop for a collection it's usually best to use for...of if you can. for loop for more complicated stuff
const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; for (let i = 0; i < cats.length; i++) { console.log(cats[i]); }
break statement.
a break statement will immediately exit the loop and make the browser move on to any code that follows it.
continue statement
instead of breaking out of the loop entirely, it skips to the next iteration of the loop.
Example of continue statement
const para = document.querySelector('p'); const input = document.querySelector('input'); const btn = document.querySelector('button'); btn.addEventListener('click', () => { para.textContent = 'Output: '; const num = input.value; input.value = ''; input.focus(); for (let i = 1; i <= num; i++) { let sqRoot = Math.sqrt(i); if (Math.floor(sqRoot) !== sqRoot) { continue; } para.textContent += `${i} `; } });
Example of break statement
const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975']; const para = document.querySelector('p'); const input = document.querySelector('input'); const btn = document.querySelector('button'); btn.addEventListener('click', () => { const searchName = input.value.toLowerCase(); input.value = ''; input.focus(); para.textContent = ''; for (const contact of contacts) { const splitContact = contact.split(':'); if (splitContact[0].toLowerCase() === searchNa…
The while loop structure
initializer while (condition) { // code to run final-expression }
While loop example
const cats = ['Pete', 'Biggles', 'Jasmine']; let myFavoriteCats = 'My cats are called '; let i = 0; while (i < cats.length) { if (i === cats.length - 1) { myFavoriteCats += `and ${cats[i]}.`; } else { myFavoriteCats += `${cats[i]}, `; } i++; } console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
the do...while loop structure
const cats = ['Pete', 'Biggles', 'Jasmine']; let myFavoriteCats = 'My cats are called '; let i = 0; while (i < cats.length) { if (i === cats.length - 1) { myFavoriteCats += `and ${cats[i]}.`; } else { myFavoriteCats += `${cats[i]}, `; } i++; } console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
do...while vs. while
The main difference between a do...while loop and a while loop is that the code inside a do...while loop is always executed at least once.
do...while example
const cats = ['Pete', 'Biggles', 'Jasmine']; let myFavoriteCats = 'My cats are called '; let i = 0; do { if (i === cats.length - 1) { myFavoriteCats += `and ${cats[i]}.`; } else { myFavoriteCats += `${cats[i]}, `; } i++; } while (i < cats.length); console.log(myFavoriteCats); // "My cats are called Pete, Biggles, and Jasmine."
Must do for all loops
you must make sure that the initializer is incremented or, depending on the case, decremented, so the condition eventually becomes false. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. Infinite loop
const para = document.createElement('p');
creates a new paragraph.
output.appendChild(para);
appends the paragraph to the output <div>.
para.textContent = —
makes the text inside the paragraph equal to whatever you put on the right-hand side, after the equals sign.
When to use for...of loop?
If you're iterating through an array or some other object that supports it, and don't need access to the index position of each item
When to use for, while, and do...while loops?
for, while, and do...while loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive.
What is the DOM?
The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage - a tree of “nodes” with different relationships depending on how they’re arranged in the HTML document.
<div id="container"> <div class="display"></div> <div class="controls"></div> </div> Explain its DOM:
the <div class="display"></div> is a “child” of <div id="container"></div> and a sibling to <div class="controls"></div>. Think of it like a family tree. <div id="container"></div> is a parent, with its children on the next level, each on their own “branch”.
How to target nodes
Selectors: Relational and CSS style. a combination of CSS-style selectors and relationship properties to target the nodes you want.
One way to select nodes
CSS-style selectors
Another way to target nodes
You can also use relational selectors (i.e. firstElementChild or lastElementChild etc.) with special properties owned by the nodes.
Use CSS style to target nodes
const container = document.querySelector('#container'); // selects the #container div (don't worry about the syntax, we'll get there) const controls = document.querySelector('.controls'); // selects the .controls div
Use relational selectors
console.dir(container.firstElementChild); // selects the first child of #container => .display console.dir(controls.previousElementSibling); // selects the prior sibling => .display
Explain DOM methods?
One of the primary differences is that these nodes are objects that have many properties and methods attached to them. These properties and methods are the primary tools we are going to use to manipulate our webpage with JavaScript
Query Selectors
element.querySelector(selector) returns a reference to the first match of selector element.querySelectorAll(selectors) returns a “nodelist” containing references to all of the matches of the selectors
Important note about querySelectorAll:
It’s important to note that when using querySelectorAll, the return value is not an array. It looks like an array, and it somewhat acts like an array, but it’s really a “nodelist”. if problems arise, is to convert the nodelist into an array. You can do this with Array.from() or the spread operator.
What does the Array.from()?
The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
Array.from() example 1:
console.log(Array.from('foo')); // Expected output: Array ["f", "o", "o"] console.log(Array.from([1, 2, 3], x => x + x)); // Expected output: Array [2, 4, 6]
Array.from() example 2:
const set = new Set(["foo", "bar", "baz", "foo"]); Array.from(set); // [ "foo", "bar", "baz" ]
Array.from() never creates a sparse array. If the arrayLike object is missing some index properties, they become undefined in the new array.
Array.from() example 3:
// Create an array based on a property of DOM Elements const images = document.querySelectorAll("img"); const sources = Array.from(images, (image) => image.src); const insecureSources = sources.filter((link) => link.startsWith("http://"));
Element Creation with DOM:
document.createElement(tagName, [options]) creates a new element of tag type tagName.
Example of element creation:
const div = document.createElement('div');
What does the element creation do and not do?
This function does NOT put your new element into the DOM - it simply creates it in memory. This is so that you can manipulate the element (by adding styles, classes, ids, text, etc.) before placing it on the page
How to add elements to your DOM?
parentNode.appendChild(childNode) appends childNode as the last child of parentNode parentNode.insertBefore(newNode, referenceNode) inserts newNode into parentNode before referenceNode
How to remove elements from your DOM:
parentNode.removeChild(child) removes child from parentNode on the DOM and returns a reference to child
How to alter elements?
When you have a reference to an element, you can use that reference to alter the element’s own properties.
Example of element alteration:
const div = document.createElement('div'); // creates a new div referenced in the variable 'div'
Example of adding Inline Style in DOM:
div.style.color = 'blue'; // adds the indicated style rule div.style.cssText = 'color: blue; background: white;'; // adds several style rules div.setAttribute('style', 'color: blue; background: white;'); // adds several style rules
Note for Adding Inline style. Kebab style CSS cased rule:
you’ll either need to use camelCase or you’ll need to use bracket notation instead of dot notation. div.style.background-color // doesn't work - attempts to subtract color from div.style.background div.style.backgroundColor // accesses the div's background-color style div.style['background-color'] // also works div.style.cssText = "background-color: white;" // ok in a string
Editing Attributes in DOM:
div.setAttribute('id', 'theDiv'); // if id exists, update it to 'theDiv', else create an id // with value "theDiv" div.getAttribute('id'); // returns value of specified attribute, in this case // "theDiv" div.removeAttribute('id'); // removes specified attribute
Working with classes DOM:
div.classList.add('new'); // adds class "new" to your new div div.classList.remove('new'); // removes "new" class from div div.classList.toggle('active'); // if div doesn't have class "active" then add it, or if // it does, then remove it
Whats standard when working with classes in DOM:
It is often standard (and cleaner) to toggle a CSS style rather than adding and removing inline CSS.
How to add HTML content in DOM:
div.innerHTML = '<span>Hello World!</span>'; // renders the HTML inside div
Why to use .innerHTML sparingly?
innerHTML should be used sparingly as it can create security risks if misused instead use .innerText
When to use innerHTML?
Inject Dynamic HTML into ur page.
Prevent security risks when using .innerHTML?
Makes sure its not provided by the user unless you first escape the user's input by making the sure it all renders as string.
How to apply js DOM to the HTML file
<head> <script src="js-file.js" defer></script> </head>
Ways to make JavaScript react to events:
You can specify function attributes directly on your HTML elements or you can set properties of form on[eventType] (onclick, onmousedown, etc.) on the DOM nodes in your JavaScript or you can attach event listeners to the DOM nodes in your JavaScript.
Prefered method to make JavaScript react to events:
Event listeners are definitely the preferred method, but you will regularly see the others in use, so we’re going to cover all three.
Explain Event Method 1: specify function attributes:
<button onclick="alert('Hello World')">Click Me</button>