JavaScript Basics .b

110 flashcards · Programming Languages · by Mae000

  1. Accessing the Last Array Element

    const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[fruits.length - 1];

  2. 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>";

  3. 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>"; }

  4. 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

  5. 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

  6. 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

  7. 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"

  8. 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

  9. The Difference Between Arrays and Objects

    In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes.

  10. 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.

  11. Create empty array

    const points = new Array(); const points = [];

  12. 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];

  13. How to Recognize an Array

    typeof returns object To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray()

  14. 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;

  15. One method to convert an array to string

    The JavaScript method toString() converts an array to a string of (comma separated) array values.

  16. 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:

  17. Popping method, Array

    Popping items out of an array The pop() method removes the last element from an array:

  18. Save a value that was popped out

    const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.pop();

  19. Shifting elements

    The shift() method removes the first array element and "shifts" all other elements to a lower index.

  20. Save a value that was shifted

    const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.shift();

  21. Add a new value using the length method

    const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi";

  22. 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.

  23. Merging (Concatenating) Arrays

    The concat() method creates a new array by merging (concatenating) existing arrays

  24. 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);

  25. 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);

  26. The concat() method can also take strings as arguments:

    const arr1 = ["Emil", "Tobias", "Linus"]; const myChildren = arr1.concat("Peter");

  27. 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");

  28. 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

  29. you can use splice() to remove elements without leaving "holes" in the array

    const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1);

  30. 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.

  31. JavaScript Array slice()

    The slice() method slices out a piece of an array into a new array.

  32. 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);

  33. Some slice method rules

    The slice() method creates a new array. The slice() method does not remove any elements from the source array.

  34. 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);

  35. 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);

  36. 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.

  37. 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.

  38. Looping through a collection: types

    Array, set, Map

  39. 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.

  40. The loop for an array

    const cats = ['Leopard', 'Serval', 'Jaguar', 'Tiger', 'Caracal', 'Lion']; for (const cat of cats) { console.log(cat); }

  41. 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" ]

  42. 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" ]

  43. 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.

  44. 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);

  45. Basic for loop structure

    for (initializer; condition; final-expression) { // code to run }

  46. 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.

  47. 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.

  48. 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.

  49. 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 = '');

  50. 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]); }

  51. break statement.

    a break statement will immediately exit the loop and make the browser move on to any code that follows it.

  52. continue statement

    instead of breaking out of the loop entirely, it skips to the next iteration of the loop.

  53. 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} `; } });

  54. 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…

  55. The while loop structure

    initializer while (condition) { // code to run final-expression }

  56. 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."

  57. 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."

  58. 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.

  59. 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."

  60. 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

  61. const para = document.createElement('p');

    creates a new paragraph.

  62. output.appendChild(para);

    appends the paragraph to the output <div>.

  63. para.textContent = —

    makes the text inside the paragraph equal to whatever you put on the right-hand side, after the equals sign.

  64. 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

  65. 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.

  66. 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.

  67. <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”.

  68. How to target nodes

    Selectors: Relational and CSS style. a combination of CSS-style selectors and relationship properties to target the nodes you want.

  69. One way to select nodes

    CSS-style selectors

  70. Another way to target nodes

    You can also use relational selectors (i.e. firstElementChild or lastElementChild etc.) with special properties owned by the nodes.

  71. 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

  72. Use relational selectors

    console.dir(container.firstElementChild); // selects the first child of #container => .display console.dir(controls.previousElementSibling); // selects the prior sibling => .display

  73. 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

  74. 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

  75. 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.

  76. What does the Array.from()?

    The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

  77. 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]

  78. Array.from() example 2:

    const set = new Set(["foo", "bar", "baz", "foo"]); Array.from(set); // [ "foo", "bar", "baz" ]

  79. Array.from() never creates a sparse array. If the arrayLike object is missing some index properties, they become undefined in the new array.

  80. 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://"));

  81. Element Creation with DOM:

    document.createElement(tagName, [options]) creates a new element of tag type tagName.

  82. Example of element creation:

    const div = document.createElement('div');

  83. 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

  84. 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

  85. How to remove elements from your DOM:

    parentNode.removeChild(child) removes child from parentNode on the DOM and returns a reference to child

  86. How to alter elements?

    When you have a reference to an element, you can use that reference to alter the element’s own properties.

  87. Example of element alteration:

    const div = document.createElement('div'); // creates a new div referenced in the variable 'div'

  88. 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

  89. 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

  90. 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

  91. 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

  92. 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.

  93. How to add HTML content in DOM:

    div.innerHTML = '<span>Hello World!</span>'; // renders the HTML inside div

  94. Why to use .innerHTML sparingly?

    innerHTML should be used sparingly as it can create security risks if misused instead use .innerText

  95. When to use innerHTML?

    Inject Dynamic HTML into ur page.

  96. 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.

  97. How to apply js DOM to the HTML file

    <head> <script src="js-file.js" defer></script> </head>

  98. 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.

  99. 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.

  100. Explain Event Method 1: specify function attributes:

    <button onclick="alert('Hello World')">Click Me</button>