old cards Flashcards

(108 cards)

1
Q

list the “getEl” methods used to traverse the DOM & and what they return.

________________________________________________________________________________________________

then describe what this code could/should be doing on a page & what the last line’s value would be :

(1)
document.getElementsByClassName(‘special’);
// value —-> HTMLCollection(3) [p.special, li.special, li.special]

(2)
const ul = document.getElementsByTagName(‘ul’)[0]
(3)
ul.getElementsByClassName(‘special’);
// —> what would this value be?
(4)
ul.getElementsByTagName(‘li’);
// —> what would this value be?

A

getElementById(‘idNameAsAString’) — returns the element as an object that has that id, if there’s no element with that id it returns null

getElementsByTagName(‘elementTagNameAsAString’) — returns the elements in an array-like object that you can iterate over (key = index, value = one of the elements; the element itself is an object with its own properties and methods); returns an empty object if there are no elements on the document that match the tag passed in
*note the ‘s’ in the method name - tells you you’ll get a collection back

getElementsByClassName(‘classNameAsString’) — returns the elements in an array-like object that you can iterate over (key = index, value = one of the elements in the class; the element itself is an object with its own properties and methods);
*note the ‘s’ in the method name - tells you you’ll get a collection back

______________________________________________________________________________________________________________________________________________________

(1) selects all elements in the class special, happens to be a paragraph and two list elements

(2) store the first ul on the page in a constant

(3) selects all elements within the first ul on the page that’s has the class ‘special’
// HTMLCollection(2) [li.special, li.special]

(4) selects all li elements within the first ul
// HTMLCollection(3) [li.special, li, li.special]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

describe the “swiss army knife” of document selectors and it’s two forms

bonus question : what is this —> #

A

querySelector
can do everything the ‘get Element(s) By’ methods do and can select anything. pass in a CSS selector as a string.

examples :

—-> by element type, like ‘h2’
—-> by id, like ‘#red’
—-> by class, like ‘section ul li.big’, which selects the first li with a class of big nested in a ul, which itself is nested in a section)
—-> by attribute, like ‘input[type=”password”], which selects the first input with the type password

it selects only the first match and returns the element in an object

______________________________________________________________________________________________________________________________________________________

querySelectorAll
same as querySelector, except it returns all matches in an array-like object
______________________________________________________________________________________________________________________________________________________

—> octothorpe

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

list & describe the properties needed to do the following :

access/reassign text inside an element

access/reassign HTML code inside an element

access the element one step up on the DOM tree

access element(s) one step down on the DOM tree

A

innerText property —- returns all of the text inside that element, no matter how many elements/nested elements are within the element selected; can reassign an element’s innerText value (formatted as a string). textContent is similar, slightly less useful

innerHTML —- return a string that contains everything that was written in the HTML doc in the element the property is being called on (if there’s only input tags with no actual text, for example, innerHTML would show the entire tag, attributes, etc — innerText wouldn’t show anything). innerHTML also reads tags and displays correctly.

example of the difference between the two :

if your webpage had an h1 — “My Webpage”

const heading = document.querySelector(‘h1’);
heading.innerText += ‘<b>!!!!!</b>’
// the h1 would read —> My Webpage<b>!!!!!</b>

heading.innerHTML += ‘<b>!!!!!</b>’
// the h1 would read —> My Webpage!!!!!

_________________________________________________

selectedElement.parentElement —-> returns the parent element

selectedElement.children —-> returns the children of the selected element in an array-like object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

list the methods used to manage attributes on HTML elements

A

getAttribute —
takes one argument; pass in the attribute you’re looking for on the element you calling the getAttribute property on (in a string) & it’ll return that value

setAttribute — takes two arguments, the attribute you want to set & the value you want to assign it). can also be used to conpletely change an attribute as well (you could have a checkbox input, and reassign the type to radio, for example, once you select it)

const range = document.querySelector(‘input[type=”range”]

range.getAttribute(‘max’)
// “500” —> gives the max value assigned to the max attribute for this range slider input element in your HTML

range.setAttribute(‘max’)
// “500” —> gives the max value assigned to the max attribute for this range slider input element in your HTML

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

describe the relationship between HTML / CSS / JS

A

HTML is the “what”, or the nouns, the contents, the underlying structure / bones of a webpage – headers, buttons, etc

CSS is the description/style of the structure, makes it look good (adjectives)

JS is the how – its the action that makes everything function – its the logic that determines how everything behaves

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

explain / describe the usefulness of the following tags :

paragraph (shortcut to fill with meaningless text?)

h1-h6

ol (how to add list items?)

ul (how to add list items?)

hr, br

A

paragraph element – grouping of related content (can use lorem*4 to fill in lorem ipsum text)

heading elements – don’t use for size (css can change the default sizes) – use for organizational / structural purposes (hierachy) to indicate main topics, pages should only have one H1, subtopics etc; should never have an h4 without an h3, etc — this is important for search engines to understand what is important

ordered lists (numbered) with <li></li> elements (can have nested lists, adding ol/ul within li as sub lists)

unordered lists (bulleted) with <li></li> elements

horizontal rule (line across the page), line break (start a new line)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is the name of the standardized markup structure for any html document?

what is the purpose of each section :
head
body

lastly, what is an html entity?

A

html boilerplate

  • head element contains title (tab browser & search results name) and metadata - info ABOUT the page, like title, css or scripts
  • the body, which contains the visible content of the page

an html entity starts with an ampersand and ends with a semi-colon — they are used to display special characters.

The most important entities are: (non-breaking space — to make sure two words always appear on same line together), < (less than sign), > (greater than sign) and © (copyright symbol).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

describe the usefulness of the following tags & how to manage height and width of both :
div
span

describe / give examples of semantic markup

A

div - generic, BLOCK LEVEL container to that fills the width of page — set height and width properties to whatever you want in css

span - generic, INLINE container (often used for text) — doesn’t respect normal height and width — need to set display property to inline-block, then set height and width

semantic markup adds MEANING rather than having a bunch of divs/spans.
The semantic elements in HTML5 are: <header> (often includes navigational content), <footer>, <nav>, <main>, <aside>, <article> (any self contained data), <section>, <figure>, <time> and <mark>.</mark></time></figure>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what is a form element and what does it (and the required attribute) do?

A

form element – empty container section w/ interactive controls for submitting info; action attribute specifies WHERE the form data should be sent when the form is submitted (an http request will be sent to wherever action is set to)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

what do each of the following attributes do in an input tag?
- type (list a few different types, what’s different about the radio type, and the input-type shortcut)
- placeholder
- name
- value
- id (how does this relate to label tag… also what is a label tag)
- required

…there are also other types of tags for forms that are helpful to be aware of :

button
text area
select w/ options (how does this relate to label tag)

A
  • type — text, password, checkbox, range, file; for the radio type, all options for selection must have the same name to group them all together; input:type (so, input:text or input:checkbox, etc)
  • placeholder — the words in a text box before you start typing
  • name — the label under which the data is being sent to the server; how the server recognizes the data; MANDATORY attribute (servers receive queries in a name - value pair)
  • value — for text, the value is whatever is being entered into the textbox, otherwise when the input is selected (for radio, checkbox, select/option), you must manually decide what value gets sent to the server when an option is picked
  • id — rather than a random text box or radio button floating on the webpage, this id serves as a label for what this input is indicating. you’ll need to create an associated label tag, and the for attribute will be set to the id of the input that the label is associated with
    label– associates text element with an input element (checkbox, etc); adding an id attribute in the input element, and setting the for attribute in the label element equal to the same thing links them together (it becomes a label “for” the input). The id needs to be unique for that particular label/input combo and should not be reused
  • required — doesn’t equal anything, just a browser validation put at the end of an input tag to ensure something is entered or selected before submission

button – text between the tags determines the words on the button; by default, buttons submit the form it’s a part of (if it’s outside a form, it does nothing)
select is like a list, option elements are like li
text area is a large text box with a scroller on the side for paragraph entries

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

anchor tags :

what is it, and what is it’s main attribute?

how do you create a URL from within your folders?

how do you link to other parts of the same page (also called a fragment)?

how do you jump to the top of a page?

optional :
how do you get a URL to open in a separate tag?

how do you create an email link?

A

anchor tag - hyperlink to another webpage, email address, file or some other place on the same page;
href attribute passed into tag to tell where to go when link is clicked (is the URL or path the tag points to)

forward slash to access higher folders, then to work down hierarchy to other files

add an id attribute for the section you want to jump to & create a anchor with the href attribute set to #whateverTheIdNameWas

create a anchor with the href attribute set to # (add whatever text between the tags)

optional :

set target attribute to _blank in anchor tag

set href to mailto:yourEmailAddress@gmail.com

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

practice

in an html doc in vscode:
using ONLY shortcuts — highlight a word, open command pallet and wrap it in a tag

create these two in html using emmet :
nav with a ul nested inside, with 5 li nested in ul - w/ each li having an anchor tag
&
a paragraph, div & li one after another

A

shift start <
shift alt P
wrap w/ abbrev
type tag

nav>ul>li*5>a (child, multiplication)
p+div+li (sibiling)

https://docs.emmet.io/cheat-sheet/

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

images & videos :

what happens with the object-fit property is set to cover?

when adding a video element to a page, how do you make sure there are play, volume buttons etc?

optional :
how do you get the video to start playing as soon as it loads?

how do you get the video to repeat automatically?

what is a common best practice for video tags to catch unsupported browsers?

A

image tag + src, alt attribute

image tag – embeds image into a document
source attribute = path to image you want to embed (either local or hosted somewhere else);
alt attribute = holds a text description of the image (optional but incredibly useful for accessibility)

object-fit makes sure the image covers it’s containing box (resizes and crops to prevent distortion)

video element — add the controls attribute with no value

optional:
autoplay attribute with no value

loop attribute with no value

include a statement like ‘Your browser doesn’t support videos.’ between the tags - this will show up for unsupported browsers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

table :

tr, th, td, colspan

…there’s also
thead, tbody, tfoot

A

table - only used for displaying tabular data —- ALL elements defining the table must be wrapped in table tags to show up formatted as a table

table row (defines a row of cells in a table, just a declaration like table itself — not visible until you add cells)

header cell & data cell – creates actual cells within the row

colspan is an attribute that allows cell to span multiple rows

thead, tbody, tfoot – just declare/define parts of a table

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

how do you connect an html and css file?

A

link tag in the head of html boilerplate; href attribute should point to the style sheet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

review these useful properties :

border (list the values)
overflow
text-align
font-weight
text-decoration
line-height
font-size
letter-spacing
font-family (first choice, backup font or generic family name)

A

https://www.cssfontstack.com/

border — width style color (any of these can be left out and it’ll still work)
overflow — if you have a fixed size container and the content spills out, you can set this to auto to allow for scrolling (bar shows up when content overflows, bar is hidden if not)
text-align – left, center, right aligned
font-weight – boldness
text-decoration – decorative lines on text (color, under/over/through, thickness, dotted/dash/wavy etc)
line-height — space around characters (think college vs wide ruled)
font-size
letter-spacing — space between letters
font-family (first choice, backup font or generic family name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

what are pseudoclasses and what is their syntax?

A

color + keyword (no space) that’s added to an element based on its position in a family (nth-of-type, first-of-type, nth child) OR how the element is being interacted with by the user (‘checked’ for radio buttons or checkboxes, ‘hover’ for images, divs, links, etc, ‘visited’ for hyperlinks, ‘active’ etc)

.post button:hover {
color : orange;
}
/* every button created within an element in the post class will turn orange when the user hovers over it */

MDN : A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They target some bit of your document that is in a certain state, behaving as if you had added a class into your HTML.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

describe syntax & define the following terms :

rule

class

id

A

idName {

rule : used to style all instances of the selected element

selector {
property : value;
}

h1,h2 {
property : value;
}

(DON’T forget semicolons! needed at the end of property declarations for the effects to take place)

___________________________

class : used to style all elements with this given class
.className {
property: value;
}

___________________________

id :
ids can be added to any element as a hook to whatever style you create for that specific element. only one element should have one id – keep these to a minimum & don’t overdo them

property : value;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

products p {

practice :

do the following using emmet abbreviations

create three section elements with an id whose value is set to “product”

create an article with an h1 whose class is “returns”

what would this relational selector do? :

color : red; }
A

section#product

article.returns*3

(1) every paragraph in the section with the id “products” will turn red

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

what are pseudo-element selectors? describe the syntax and give a few examples

A

MDN : Pseudo-elements act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements. Pseudo-elements start with a double colon.

April’s thoughts : pseudo-classes decide how an element is styled based on their state (hovered over, clicked, being the nth occurrence of its type, etc). Pseudo-elements style parts of an actual element that can’t normally be selected on its own (there’s no first letter element)

::first-letter
::first-line (first line of paragraph)
::selection (changes color of what’s highlighted)
::before or ::after (to insert something before/after the content of an element — you set the content selector to whatever you want & the display selector to block)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

other styling details :

which color system(s) can you use to change the opacity of a color?

describe the values for the border and border-width properties

A

rbga or hsla (a is alpha, set between 0 and 1 for opacity)

border : width (10px) style (solid) color (royalblue);
border-width : top (10px) right(20px) bottom(10px) left(20px) OR 10px 20px; — clockwise

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

positioning :

what is z-index?

relative vs absolute vs fixed positioning

font measurements : px, %, vh/vw, rem

float property

A

the z-index property moves elements along the z-axis and controls depth (imagine the computer screen is at 0 depth). this can move an element in front of (1 or greater z-index which brings the element towards you) or behind other elements (z-index : -1)

relative : set/move elements around relative to it’s normal/default position
absolute : set/move elements around relative to the container (container position must be relative, moving element must be absolute)
fixed : set/move elements based on the viewport

px : absolute & not responsive
% : certain percentage of parent element
vh/vw : percent of viewport height or width
rem : element size will adjust based on default font size which you can set

float property

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

talk through these lines :

  • function multiplyBy2 ( ) { }
  • const result = multiplyBy2 ( );
  • return multiplyBy2;
A

“creating a function, labeled multiplyBy2 and storing the function definition in XXXXX memory” —- global memory if out in the open, otherwise its local

“creating a constant called result in in XXXXX memory, and assigning it the evaluated result of invoking multiplyBy2”

“return the function definition of multiplyBy2”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

order the steps in which you’d read through this code, line by line and explain what’s happening in each step :

\_\_ function outer ( ) {
  \_\_ let counter = 0;
  \_\_ function incrementCounter ( ) {
    \_\_ counter ++;
  }
  \_\_ return incrementCounter;
}
\_\_ const myNewFunction = outer( );
\_\_ myNewFunction( );
\_\_ myNewFunction( );
A
1 function outer ( ) {      ===> create a function labeled outer, and STORE THE FUNCTION DEFINITION in global memory
  3 let counter = 0;      ===> declare a variable labeled counter & assign counter the value of zero
  4 function incrementCounter ( ) {      ===> create a function labeled incrementCounter & store the func def in local memory 
    "7" & "9" counter ++;       ===>
  }
  5 return incrementCounter;      ===> return the func def of increment counter and store in global constant myNewFunction
}
2 const myNewFunction = outer( );       ===> declare a constant myNewFunction & assign it the return value of the invocation of the function outer* 
6 myNewFunction( );        ===> invoke myNewFunction** (functionality formerly known as incrementCounter aka counter++)
"8" myNewFunction( );       ===> invoke myNewFunction** (functionality formerly known as incrementCounter aka counter++)

*this means myNewFunction takes on the definition of incrementCounter (aka THE FUNCTIONALITY OF INCREMENT COUNTER => counter++); so when you invoke myNewFunction, you’re essentially just incrementing counter – also note that the same function definition has multiple labels, one within a local execution context & one in global memory

**even though we look back up the page to incrementCounter, JS is looking at the returned function definition of incrementCounter stored in myNewFunction

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
explain any "backpacking" going on here (what's in the backpack, which function does it belong to) : ``` function outer ( ) { let myNewCounter = 14; let counter = 0; function incrementCounter () { counter ++; } return incrementCounter; } ``` const myNewFunction = outer( ); myNewFunction(); myNewFunction();
the backpack contains counter but not myNewCounter, because myNewCounter is not referenced in incrementCounter. Once incrementCounter's func def is returned out, JS sees that counter is referenced but not myNewCounter, so it only links counter to incrementCounter's func def. the constant myNewFunction is assigned the return value of function outer, which is the function definition of incrementCounter PLUS the attached persistent lexically-scoped reference data (data in the surrounding the variable environment) -- counter variable. since counter won't be found in the local context of myNewFunction, the next place JS will look is the backpack. myNewFunction has two memories --- the temporary local memory that's renewed/empty every time you invoke the function. But then, it has a second memory that persists... myNewFunction holds a grudge and that bit of persistent memory sticks around and remains attached to the function definition where you can store stuff in it & grab stuff from it from inside the running of the new function [[scope]] is the hidden property that links the surrounding local memory to incrementCounter -- when incrementCounter's definition gets returned and stored in myNewFunction, incrementCounter brings the hidden property with it & therefore drags out the local memory with it
26
describe and list syntax for : descendant selectors
parent nestedEl { property: value; } (could also be .parent, #parent) styles all of the nested elements within a particular parent element or class; parent remains unchanged REVIEW ME! ....there are also adjacent selectors el1 + el2 { } select only the el2 that are right after el1 (immediately preceded by) & direct-descendant / direct-child selectors el1 > el2 { } any el2 that's directly descended from el1 & attribute selectors - allows you to style elements with a particular attribute input[type="password"] { }
27
what are pseudoclasses and what is their syntax? give a few examples
keyword added to a selector that specifies the state of the selected/styled elements :hover :checked :nth-of-type() :active :first :not() ex: .post button:hover { } when you hover over a button inside an element in the post class
28
READ ONLY FLASHCARD : describe the difference between function, block and lexical scope what is hoisting?
Variable scope is the location where a variable is defined and the context where other pieces of your code can access and manipulate it function - the variable is visible only within a function, and it cannot be accessed outside the curly brackets of the function block - the area within if, switch conditions and for, while loops; those variables exist only within the corresponding block lexical - the childrens' scope has access to the variables declared in the parent scope Hoisting - refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.
29
describe the anatomy of a : (1) css rule (four parts) (2) html element (four parts)
(1) selector { property : value; —> this is a declaration } (2) content
30
GO BACK THROUGH TOP & FILL OUT THIS CARD (1) universal selector type selector class vs id selectors, when id would be useful grouping selectors vs chaining selectors — syntax and when to use either one descendant combinator — syntax and how it works direct descendant combinator — syntax and how it works color background-color font-family — syntax font-size — syntax font-weight — syntax & valid values text-align — purpose border? padding? margin? display? how to adjust an image’s size without losing it’s proportions (here) + what should you always include for image elements and why basic specificity cascade (most to least — 3 selectors) https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors
(1)
31
describe the return rules/structure for components (multi-line, single line components)
multi-line —> for the body of the component, wrap in curly braces. for the return statement, you need a set of parens & within it, nest a div or fragment, and within the div/frag nest your returned JSX single-line —> can be the same as multiline, or just a set of parens instead of curly braces, and the single line of code with no div/frag
32
describe the steps and code involved in generating a random number
1. generate random number (Math.random( )) 2. Think about the max and min in the range — if the min is zero, add one to the max 3. The random number generated is between 0.0 and 0.99, so multiply it by your max number (Math.random( ) * max) 4. floor the random number (Math.floor(Math.random( ) * max) 5. Add on the min at the end if it’s greater than zero (Math.floor(Math.random( ) * max) + min
33
describe the difference between properties and methods
properties are keys in an object whose values hold data / information methods are properties / keys with a function definition (value)
34
what is a constructor function and how is it declared differently from a regular function? *remember, you can also use the constructor property to determine an object’s constructor function (object.constructor - like the length property) what is the purpose of creating a constructor function? describe what's within the body of a constructor function
its the function that is used to create a particular object, and constructors are named using pascal notation (as opposed to camelcase for traditional & factory functions) It creates a "blueprint" for creating many objects of the same type by being able to call the constructor using the new keyword the "this" keyword is used (almost as a substitute for the new object that'll be created) --- really, "this" points to the new object https://www.w3schools.com/js/js_this.asp
35
what happens when you use the "new" operator to call a constructor function?
the new operator : 1. creates an empty object 2. sets the "this" keyword used to create key value pairs in the constructor function to point to that empty object 3. it returns the object
36
in the object below, what does the "this" keyword point to? how would you return "John Doe" in the console? const person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } };
in an object literal method, "this" points to the object its being used within — console.log(person.fullName());
37
generally, what does the 'this' keyword point to? what does 'this' point to when used in a method? what does 'this' point to when used inside a constructor function?
'this' references the object that is executing the current function. when used in a method (function definition of a property within an object), 'this' references the object the method is in. when a new object ('instance’) is created using the constructor function - the 'new' keyword creates an empty object, makes the 'this' keyword within the constructor point to the new object, and it returns it. so 'this' refers to the new object that has been created by the new operator https://codewithmosh.com/courses/324741/lectures/5142768
38
describe the difference between a factory function and a constructor function
a factory function creates and returns an object literal function createCircle(radius) { return { radius, draw ( ) { console.log('draw : circle with radius of ' + radius); } } } const circle = createCircle(1); circle.draw(); a constructor function creates and returns an object using the new operator and this keyword (essentially, altogether it creates and then points to an object) function Circle(radius) { this.radius = radius; this.draw = function () { return 'draw'; } } const another = new Circle(1);
39
what is "abstraction" and how do you implement this OOP principle in JS? elaborate on your knowledge :)
Abstraction = "hide the (implementation) details, expose only the essentials (public interface)" you don't want everything in your object to be public and accessible from the outside (if every method you create inside an object is traditionally declared, anyone at any time can call the method and change the value/function associated with it) implement using private properties and methods : instead of setting properties/methods, define them as local variables to be used within the object. you can create a method that utilizes the local variables within its function (the variables become PLSRD), taking advantage of closure -- the method value can be the child function, the constructor func is the parent https://codewithmosh.com/courses/310571/lectures/4881074
40
what is a prototype?
just a regular-shmegular parent -- prototype is a property with an object value (children inherit all of the methods / props defined in its prototype)
41
how would you turn this constructor function into an ES6 "class"? *sprankle some shuga on it* function Circle(radius) { this.radius = radius; this.draw = function () { console.log('draw'); } } const c = new Circle(1);
// class keyword, class name, curly braces to set up the body of the class // class keywords ARE constructor functions class Circle { // constructor method used to initalize objects constructor (radius) { // PROPERTIES are defined within the constructor method this.radius = radius; } // METHODS are defined within the body of the class & is added to the prototype of the object (can be defined within the constructor to have it on the object instance) // no function keyword used, just method name, parens & braces draw () { return 'draw'; } } const c = new Circle(1);
42
how would you create a circle class, and have it inherit from the Shape class below? class Shape { move() { console.log('move'); } }
class Circle extends Shape { draw () { return 'draw'; } } const c = new Circle(); console.log(c.move()); // 'move' https://codewithmosh.com/courses/310571/lectures/4881373
43
flashcard to make : define the other three pillars of OOP outside of abstraction (encapsulation, inheritance and polymorphism)
https://codewithmosh.com/courses/310571/lectures/4880998
44
flashcard to make : get a good feel for getters and setters
https://www.youtube.com/watch?v=qkAb-4ZR5Yw&t=67s
45
flashcard to make : get an understanding of subclasses watching video, then try csbin extensions on subclasses
https://www.youtube.com/watch?v=khuDeNwXkfI http://csbin.io/oop
46
flashcard to make : learn about mixins, then try csbin extension on mixins
https://codewithmosh.com/courses/310571/lectures/4881279 http://csbin.io/oop
47
how would you remove the draw method from the Circle object and add it to Circle's prototype object? After doing this, what would the following test cases log to the console? console.log(c1); console.log(c2.draw()); console.log(Circle.prototype); function Circle(radius) { this.radius = radius; this.draw = function () { return 'draw'; } } const c1 = new Circle (4); const c2 = new Circle (2);
function Circle(radius) { // this is an instance member this.radius = radius; } // this is a prototype member Circle.prototype.draw = function () { return 'draw'; } const c1 = new Circle (4); const c2 = new Circle (2); console.log(c1); // Circle {radius : 4} console.log(c1.draw()); // 'draw' console.log(Circle.prototype); // Circle { draw: function () { return 'draw'; } }
48
where the keyword "this" is placed determines what object it's referencing. How do you determine what "this" references?
if wrapped inside a constructor function or class, it references a particular instance of the constructor / class. if wrapped inside an object, it refers to that object. EX : function Circle(radius) { this.radius = radius; } Circle.prototype.toString = function () { return 'Circle with radius' + this.radius; // this points to toString, which is on the prototype object of Circle - so this still points to whatever radius is passed into Circle for a particular instance } const c1 = new Circle (4); const c2 = new Circle (2);
49
Spread some "syntactic sugar" on this bish function UserCreator (name, score) { this.name = name; this.score = score; } UserCreator.prototype.increment = function() { this.score++; }; UserCreator.prototype.login = function () { console.log("login"); }; const user1 = new UserCreator("Eva", 9); user1.increment();
class UserCreator { constructor (name, score) { this.name = name; this.score = score; } increment() { this.score++; } login() { console.log("login"); } } const user1 = new UserCreator("Eva", 9); user1.increment();
50
generally, what does the 'this' keyword point to? what does 'this' point to when used in a method? below, that does the "this" keyword point to? how would you return "draw" to the console? function Circle(radius) { this.radius = radius; this.draw = function () { return 'draw'; } } const another = new Circle(1);
'this' references the object that is executing the current function. when used in a method (function definition of a property), 'this' references the object the method is in. https://codewithmosh.com/courses/324741/lectures/5142768 "this" points to the object that was created by the "new" keyword, stored in the constant labeled another console.log(another.draw());
51
can use codesmith videos, JS for Beginners - section 12, section 19 for a more in depth review
52
what does the new keyword do (list four)?
1. creates an empty object 2. points the keyword "this" to the current object being created (on L hand side of ' = new') 3. links the new object’s private prototype property (___proto___) to the value of the constructor function’s prototype object, which contains methods 4. returns the object
53
what convention do we use for constructor functions that lets other devs know that the keyword "new" is needed to create a copy of that function?
all capital letters for each word in the function name
54
describe the components of a JS class — break down the syntactic sugar
class FunctionName { constructor (param1, param2) { this.prop = val1; this.prop = val2; } method1 ( ) { this.functionality1; } method2 ( ) { this.functionality2; } } a constructor function that populates the key-value pairs (data / information), beneath that are methods that are added to prototype property/object on FunctionName (the class has a prototype property where we store method 1 & 2 for access as needed) see the 1 hour & 3 minutes mark of this video : https://www.youtube.com/watch?v=aAAS9cEuFYI
55
Using an array as an example, describe the difference between : Array.prototype and __proto__
"prototype" is a property on the Array with an object literal value. the object holds the methods (map, forEach, find, includes, push, pop etc) __proto__ is a private property name used to reference to the Array.prototype object on individual instances of different arrays you create
56
four pillars of OOP (list, define/how do we implement, share benefits) & why do we use OOP?
IPEA inheritance : eliminates redundant code by allowing instances of a "parent" object to inherit methods from the parent without having to redefine methods and properties repeatedly polymorphism : "many forms", or representing an object in different forms —- ex : you can extend a parent class and take advantage of method overriding, while still having access to all parent properties and methods (https://www.youtube.com/watch?v=XxMUJ9-Pb2E) encapsulation : group related variables and functions that operate on them (rather than decoupling them) —- reduces complexity & increases reusability abstraction ("microwave") : hiding the implementation details & showing only the essential data to users by creating local variables that create values that public implementation can be built on, but is not accessible to the public — this creates a simpler interface (reduces complexity) & reduces the impact of change (https://www.youtube.com/watch?v=jM0WcyQWMSM) (https://codewithmosh.com/courses/310571/lectures/4881074) we use OOP because functional / procedural programming (where we have data stored in variables and a bunch of functions that operate on that data) — as straightforward as it is, the functions end up being less DRY and more interdependent —- changing code in one function may cause others to break which is problematic. grouping related variables and functions into a unit (object) https://codewithmosh.com/courses/310571/lectures/4880998
57
Describe what the following do : Object.create(null) Object.assign ( ) Object.entries ( ) Object.keys ( ) Object.values ( ) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
Object.create (null) —- creates an empty object regardless of what’s passed in, the argument determines what the __proto__ value is (the value is an object with methods to available to be accessed by the empty object) Object.assign ( ) Object.entries ( ) Object.keys ( ) Object.values ( )
58
describe the difference between a factory and constructor function
a factory function creates an object and returns it all on it’s own. constructor functions don’t return the object they create, so you have to use the new keyword to instantiate a new instance object //This functions makes and returns an object every time it is called. // The resulting objects all follow the same "recipe" function makeColor(r, g, b) { const color = {}; color.r = r; color.g = g; color.b = b; color.rgb = function() { const { r, g, b } = this; return `rgb(${r}, ${g}, ${b})`; }; return color; } const firstColor = makeColor(35, 255, 150); firstColor.rgb(); //"rgb(35, 255, 150)" const black = makeColor(0, 0, 0); black.rgb(); //"rgb(0, 0, 0)" _____________________________________________________________________________________________________ // This is a Constructor Function... function Color(r, g, b) { this.r = r; this.g = g; this.b = b; } //If you call it on its own like a regular function... Color(35, 60, 190); //undefined //It returns undefined. Seems useless! // ***************** // THE NEW OPERATOR! // ***************** // below are separate methods (rgb, hex, rgba) that are being added to Color’s prototype object (this protyotype object is the value assigned the the instance-of-Color’s ___proto__ private property. Color.prototype.rgb = function() { const { r, g, b } = this; return `rgb(${r}, ${g}, ${b})`; }; Color.prototype.hex = function() { const { r, g, b } = this; return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }; Color.prototype.rgba = function(a = 1.0) { const { r, g, b } = this; return `rgba(${r}, ${g}, ${b}, ${a})`; }; const color1 = new Color(40, 255, 60); color1.hex(); const color2 = new Color(0, 0, 0); color2.hex();
59
describe the rules that govern the "this" keyword :
"this" is an implicit parameter assigned by JS at runtime any time you execute a method, this evaluates to whatever object the method is attached to (whatever’s to the left of the dot)
60
extends super subclasses https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420
// Pet is the base / super class // Dog and Cat are other classes with common functionality that extend from Pet // In the class Cat, it has its own unique information (livesLeft param) that it adds to an object instance, but it also can call super, which will reference the constructor of it’s super class (Pet) class Pet { constructor(name, age) { console.log('IN PET CONSTRUCTOR!'); this.name = name; this.age = age; } eat() { return `${this.name} is eating!`; } } class Cat extends Pet { constructor(name, age, livesLeft = 9) { console.log('IN CAT CONSTRUCTOR!'); super(name, age); this.livesLeft = livesLeft; } meow() { return 'MEOWWWW!!'; } } class Dog extends Pet { bark() { return 'WOOOF!!'; } eat() { return `${this.name} scarfs his food!`; } } extends — you can extend Dog to have access to the constructor and methods in the Pet class (as opposed to repeating the same constructor in Cat & Dog + the same method, eat) — if they’re common constructors/methods for multiple classes, you can extend rather than repeat super — references the super class (the class you’re extending from)
61
REVIEW FLASHCARD (no need to actively recall) : getter & setter
both of these create the appearance of a property on an instance with the functionality of a method (outside of the class, it’s accessed w/o parens — a computed property) get : getters allows you to access data on the object, perform some logic on it, and display it to the user without giving access to user to change the method itself. set : by placing 'set' in front of a function, users can update a value that’s given/displayed clientside without having access to the logic that changes the value itself const person = { name: "Dom", job: "Web Developer", interests: ["Tennis", "Gardening"], get headline() { return `${this.name} is a ${this.job} and is mainly interested in ${this.interests[0]}.` }, set primaryInterest(val) { this.interests.unshift(val); } }; console.log(person.headline); // 'Dom is a Web Developer and is mainly interested in Tennis.' person.primaryInterest = "Home Automation"; console.log(person.headline); // 'Dom is a Web Developer and is mainly interested in Home Automation.' best video —- https://www.youtube.com/watch?v=QhFo_L_81Tc backup — https://www.youtube.com/watch?v=qkAb-4ZR5Yw
62
Object.keys — O(n) Object.values — O(n) Object.entries — O(n) Object.assign hasOwnProperty — O(n)
63
describe / explain the difference between value and reference types & how they work
value types --- primitives (number, string, boolean, undefined, null, symbol) values pass around copies of values, and are independent of one another let x = 10; let y = x; x = 5; console.log(`x is : ${x}, and y is : ${y}`); // x is 5, and y is 10 reference types --- composite (objects, functions, arrays) const obj = { one : 1, two : 2, three : 3 }; const objCopy = obj; obj.four = 4; // obj and objCopy both point to the same object in memory (diff names for the same address) -- logging both separately should show identical objects console.log(obj); console.log(objCopy); // { one: 1, two: 2, three: 3, four: 4 } // { one: 1, two: 2, three: 3, four: 4 }
64
describe the difference between pass by value and pass by reference
primitives are copied by their value let x = 10; let y = x; x = 20; // y is 10, x is 20 — they are independent of one another let x = {num : 10}; let y = x; x.num = 20; // both x & y point to an address where {num : 10} is located in memory
65
what are ES6 default parameters? what do rest params do?
Default parameters let you initialize a named parameter with default values if no value is being passed into the function function say(message='Hi') { console.log(message); } say(); // 'Hi' say('Hello') // 'Hello' The rest parameter syntax allows a function to accept an indefinite number of arguments as an array. It collects all arguments (all arguments passed in) from a function call and PUTS THEM IN AN ARRAY -- when creating the function, put '...' before the parameter name and whatever the person who's calling the function passes in as an argument will be used good reference video STARTING AT 3:06 : https://www.udemy.com/course/the-web-developer-bootcamp/learn/lecture/22003670#overview also : https://codewithmosh.com/courses/324741/lectures/5142775
66
describe the logic behind using the OR operator to assign value… get a really good feel for this!
the OR operator looks for truthiness in the first statement (an undefined value is falsy & an actual bit of data like a num, string, whatever is truthy) --- if that first value is empty, and the second value is truthy, the truth value will get returned let someInput = "" const name = someInput || 'Max' console.log(name) const votes = ['y', 'y', 'n', 'e', 'y', 'n', 'n', 'n', 'y']; const tally = votes.reduce((tally, vote) => { tally[vote] = 1 + (tally[vote] || 0); return tally; }, {}); console.log(tally)
67
const example = {sentence : "TODAY IS AN AWESOME DAY FOR CODING!"}; Create a function "fixTitle" that take an argument (a string). Your job is to have the function return the string in title case/style, meaning that each word is capitalized (all other letters in the word are lowercase). Assume passive words like "the", "and", "to" are also going to be capitazlized. example: input: "THE HiSTory of mathematiCS" output: "The History Of Mathematics" Test your fixTile function by passing in the sentence value of your "example" object.
function fixTitle (str) { return str.split(" ").map(n => { return n[0].toUpperCase() + n.slice(1).toLowerCase()}).join(" ") } console.log(fixTitle(example["sentence"]));
68
what are the syntax rules for prop values across different data types? numbers strings objects arrays booleans variables regular functions event handlers how are props used to communicate between parent and child components?
for props — strings must be wrapped with double quotes numbers/objects**/arrays/booleans/variables should be wrapped with curly braces regular functions should also be wrapped in curly braces with parens & no arguments since any calculations should be done before the return data using props event handlers should be wrapped in curly braces with no parens, we’re passing in a REFERENCE to the function as a value of the event attrinute EXAMPLE : const App = ( ) => { return ( ); } | | | | **objects can be provided as a prop, but you cannot display an object by putting an object alone between two JSX tags EXAMPLE : const App = ( ) => { const config = {color : 'red'} return ( <>

{config}

—— NOPE! —— OK! < /> ); } ___________________________________________________________________________ use the parent component to generate some data that you’ll want to display or use in the child, or just add html attributes that you’d want to use` (formatted for react) — add them to a JSX element (either an html element or a child instance of a component) react collects those attributes and puts them in an object props object shows up as the first argument to the child component function utilize the values in the props object however you wish

69
how are props utilized with html attributes ?
1. all prop names follow camel case 2. the class attribute is written as 'className' 3. in-line styles are provided as objects within props — grouped together separated by commas, structure is propName : 'value' EXAMPLE : const App = ( ) => { return ( ); }
70
describe a component’s layout
function expression, with props passed in as needed code (JS) to compute values we want to show / use in our JSX — can include functions a return statement with an outer element (div or fragment) wrapping the content we want this component to show
71
Why do we use fragments (or outermost elements) in React?
In React, JSX expressions must have only one parent element. This syntax is so because JSX is transpiled to JavaScript before execution and only one element—the parent element—can be returned from an expression.
72
how does destructuring work / what does it do in react?
destructuring allows us to extract and gather the values of an object’s properties into separate variables. rather than passing the entire props object, you can assign the values of the properties directly to variables by destructuring the props object that is passed to the component function as a parameter
73
write out and explain the structure of an App component that utilizes state to create a counter that renders to the screen and increments by one every five seconds.
// import the useState function from the react library import { useState } from 'react' const App = () => { // define a piece of state and initialize with the value zero // the useState function returns an array that has 2 items, a counter variable initialized to zero in this case + a variable setCounter which will be used to modify state const [ counter, setCounter ] = useState(0) // call the setTimeout function passing in a function to increment counter & a timeout value // The function passed as the first parameter to the setTimeout function is invoked five seconds after calling the setTimeout function // when the state-modifying function setCounter is called, React re-renders the component which means that the function body of the component function gets re-executed setTimeout( () => setCounter(counter + 1), 5000 ) return (
{counter}
) } export default App in other words : state is imported > app component is created, within the function definition… > a piece of state is defined, where our counter is initialized to zero > setTimeout is called but not executed until the allotted time > JS asychronously moves on and returns the div, which is displayed until the rendered value is updated by setCounter > the new value of counter gets rendered —- the last two steps keep repeating
74
define what the event system and state system generally do in react. what are the event handler naming conventions, and what are the steps involved in setting up an event handler? what are the steps involved in defining a piece of state?
the event system detects when the user does something in the app (click, drag, type) —- the state system is used to update content on the screen as the user interacts with the app (state is the one and only way we can change what content React shows) _____________________________________________________________________________________________________ convention —- use 'onSomething' names for props which represent events and 'handleSomething' for the function definitions which handle those events. the steps involved in setting up an event handler : - decide what kind of event you want to watch for* - create a function in the App component that determines what happens when the event occurs (this is your event handler, named 'handle + EventName') - pass the event handler as a prop to a JSX element (either a plain element or a child component) using a valid event name (onClick, onMouseOver, etc) - pass a reference to the function (wrapped in curly braces) *https://legacy.reactjs.org/docs/events.html _____________________________________________________________________________________________________ how to define a piece of state : - define a piece of state with the useState function - pass in a value to the useState function, this is the default/starting value for our piece of state - update state using setter function in the component when the user does something. this causes react to rerender component
75
describe different ways to avoid directly mutating state in React
use the spread operator to spread an existing array or object into a new one, then update the specific key-value pair as desired concat values to an existing array — this creates a shallow copy of an array with an added value (as opposed to using the push method, which mutates the array its called on directly) using join to get an string of objects from an array
76
what do we mean by the fact that state updates in React are asynchronous?
State updates using this.setState or useState do not immediately mutate the state but create a pending state transition. Accessing state immediately after calling the updater method can potentially return the old value. look at this code snippet from an App component : const [left, setLeft] = useState(0) const [right, setRight] = useState(0) const [total, setTotal] = useState(0) const handleLeftClick = () => { const updatedLeft = left + 1 setLeft(updatedLeft) setTotal(updatedLeft + right) } // const handleLeftClick = () => { // setAll(allClicks.concat('L')) // setLeft(left + 1) // setTotal(left + right) // } in the event handler for left click events, we created a new constant and stored the current value of left plus one in it, and THEN updated left using setter function to avoid issues with async updates
77
anytime you’re creating a form with an input, what is the general structure for the form?
(1) the input should have a value attribute assigned a piece of state to keep track of what is entered into the input & onChange attribute assigned the value of an event handler with the event object as parameter that sets the piece of state to whatever the user enters into the input (2) the form should be wired to an event handler that handles a form event. should have an event parameter and the 'event.preventDefault( )' method to prevent form auto-submit / page reload + whatever you want to do with the piece of state / value that has been entered, like add to the beginning or end of a larger array using spread w/o mutating original + a final update to piece of state that clears out input by setting to an empty string or whatever is appropriate adding elements to different parts of an array in react: https://state-updates.vercel.app/
78
what do you have to do in a file if you want to use a separate component?
you have to import the component in your current component and export the component in its own file
79
THREE PART QUESTION : what are string template literals & what is the syntax for them? how does the ternary operator work & what is the syntax? describe the logical AND, OR and NOT operators & how they function!
a special type of string that allows you to evaluate data inside of a string by wrapping that data in ${ } and include backticks around string const firstName = 'David'; const lastName = 'Bowie'; console.log(`My favorite artist is ${firstName} ${lastName}`) // => "My favorite artist is David Bowie" console.log(`10 + 25 = ${10 + 25}`) // => "10 + 25 = 35" ________________________________________________________ conditionalExp ? expIfTrue : expIfFalse; ________________________________________________________ && —- returns the first falsey value or the last truthy value || —- returns the first truthy value https://www.udemy.com/course/react-redux/learn/lecture/34695202#overview ! — gives the opposite of whatever it’s applied to
80
# open up CS bin to work through a few quick problems! OPEN CS BIN & COMPLETE PRACTICE PROBLEMS : let str = 'Brooklyn Queens Expressway'; let num = 2813308004; let strNum = '281330.8004'; /* TEN PRACTICE PROBS uno ——> change cases both ways of the entire string dos ——> turn num into a string & confirm the data type tres ——> turn strNum into a number (with and w/o decimals). generally, when might these tools be worth considering using? quatro ——> use 2 methods to determine if str contains the letter 'o' cinco ——> determine if str begins with 'b' and ends with 'y' seis ——> extract 'een' from the string siete ——> log 'Queens Expressway' ocho ——> replace 'Express' substring with 'High' nueve ——> replace every occurrence of the substring 'e' with an 'a' diez ——> first occurrence of 'o' in str */
uno ——> .toUpperCase( ); and .toLowerCase( ); ___________________________________________________________ dos ——> .toString( ) and typeof(value) ___________________________________________________________ tres ——> with decimals : Number(strNum) or parseFloat(strNum) + w/o decimals : parseInt(strNum) working with numeric keys in objects that you need to pass into functions as a numeric data type ___________________________________________________________ quatro ——> .includes (substring); OR .indexOf (substring); ___________________________________________________________ cinco ——> .startsWith (substring); or .endsWith (substring); ___________________________________________________________ seis ——> .slice (index at which to start extracting, optional index at which to stop extracting NOT including the character at this index) ___________________________________________________________ siete ——> .slice(index at which to start extracting) ___________________________________________________________ ocho ——> .replace(stringYouWantToReplace, replacementString); ___________________________________________________________ nueve ——> .replaceAll( stringYouWantToReplace, replacementString) ___________________________________________________________ diez ——> indexOf(string)
81
TWO PART QUESTION : all JS values have inherent truthyness or falsyness about them. List 6 falsy values! __________________________________________________________ describe the difference between null and undefined
false 0 ""(empty string with no spaces) null undefined NaN ... everything else is truthy! falsiness can be useful to determine if something is defined or if it exists / has content EXAMPLE : let loggedInUser = ''; if(loggedInUser) console.log('LOGGED IN'); else console.log('PLEASE LOG IN'); __________________________________________________________ null is the intentional absence of any value that you’ve assigned to some variable. undefined refers to variables that do not have an assigned value; usually an indicator that JS gives you (not intentional)
82
QUICK FOUR PART QUESTION : how can you ensure that a numeric value is even or odd? __________________________________________________________________________ what is the exponentiation operator? __________________________________________________________________________ using the Math object : - remove the decimal from a number - round up a number - round to the nearest integer - max or min value - generate a random number between 1 and 10 — describe what the main method does in detail __________________________________________________________________________ what is the difference between the postfix increment operator and the prefix increment operator? predict the result of logging num and result in both cases : let num = 5; let result = num++; OR let num = 5; let result = ++num;
value % 2 = 0 for even, 1 for odd __________________________________________________________________________ syntax : x ** y (2 ** 3 is the same as 2^3) __________________________________________________________________________ Math.floor (num) Math.ceil (num) Math.round (num) Math.max( ), Math.min( ) —-> arguments can be a list of numbers, or an array spread into a list of numbers Math.floor(Math.random( ) * 10) + 1 —> Math.random( ) returns a random decimal between 0 and 0.999999 (reference video : https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17032308#overview) __________________________________________________________________________ postfix increment operator — i++ the current value of the variable is used in the expression or statement first, and then the variable is incremented let num = 5; let result = num++; console.log(num); // Output: 6 (num was incremented to 6) console.log(result); // Output: 5 (result holds the initial value of num before the increment) VERSUS prefix increment operator —- ++i the value of the variable is incremented first, and then the updated value is used in the expression or statement let num = 5; let result = ++num; console.log(num); // Output: 6 (num was incremented to 6) console.log(result); // Output: 6 (result holds the value of the updated num)
83
describe the structure of switch statements & its use case. also describe how you’d combine logic in a switch statement.
USE CASE : you have one value and you’re checking it against multiple different conditions to determine output based on that changing value argument for switch : the variable you’re comparing against case : each case is a different potential value stored in variable break : need a break statement after each case’s logic, otherwise all values following will be returned/logged default : your "else" / catch-all overlapping cases : combine logic by stacking cases and applying a break ________________________________ let emoji = "heart"; // Switch with overlapping cases... in this case, with no code to run after 'heart' AND no break statement, it combines the next case with the current switch (emoji) { case "sad face": case "happy face": console.log("yellow"); break; case "eggplant": console.log("purple"); break; case "heart": case "lips": console.log("red"); break; default: console.log("no emoji entered"); } // red ________________________________ reference video : https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/16777632#overview mdn : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
84
get a general feel for regex formatting and get comfortable using test method —-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test charAt, charCodeAt… these are more performant (faster) than regex, but take longer to write this video at 10 min could be a good example —- https://www.udemy.com/course/js-algorithms-and-data-structures-masterclass/learn/lecture/11172608#overview
https://www.youtube.com/watch?v=sXQxhojSdZM https://www.youtube.com/watch?v=9RksQ5YT7FM https://www.youtube.com/watch?v=EiRGUNrz9MY https://www.youtube.com/shorts/D8HFzAaD44M
85
loop overview section 7 https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/16997986#overview
86
describe the logic behind using the OR operator to assign value… get a really good feel for this!
the OR operator looks for truthiness in the first statement (an undefined value is falsy & an actual bit of data like a num, string, whatever is truthy) --- if that first value is empty, and the second value is truthy, the truth value will get returned let someInput = "" const name = someInput || 'Max' console.log(name) const votes = ['y', 'y', 'n', 'e', 'y', 'n', 'n', 'n', 'y']; const tally = votes.reduce((tally, vote) => { tally[vote] = 1 + (tally[vote] || 0); return tally; }, {}); console.log(tally)
87
describe the high-level difference between a Set and a Map describe how to create a new set, and two ways to convert a set to an array
Map objects are similar to object literals, but the key types can be any value and they're actual iterables where you can determine the size of the map. Sets are a collection of unique values // Create a Set const letters = new Set(["a","b","c"]); //Convert to an array Array.from or spread operator const letters = ["a","b","c"]; const number = [1, 2, 3, 4]; const combo1 = [...new Set([...letters, ...number])]; console.log(combo1); // ['a', 'b', 'c', 1, 2, 3, 4] const combo2 = Array.from(new Set([...letters, ...number])); console.log(combo2); // ['a', 'b', 'c', 1, 2, 3, 4] helpful articles : https://www.w3schools.com/js/js_object_sets.asp https://www.javascripttutorial.net/es6/javascript-set/
88
/* arrays fill, flat, join, some, every, sort strings split Map / Set try / catch / finally block spread vs rest */
89
describe the function of the following object methods : assign, entries, keys, values, hasOwnProperty
assign — entries — keys —- returns the keys in an object in an array as string elements values — returns the values in an object in an array hasOwnProperty —- a method that checks for the presence of a key (passed in as an argument) & returns a boolean
90
section 23 https://www.udemy.com/course/the-web-developer-bootcamp/learn/lecture/22003578#overview
destructuring objects —
91
what is a class? define how a class is generally structured in JS.
a class is blueprint for defining an object. class Name { constructor ( ) { // holds properties this.propOne = "value"; this.propTwo = "valuetwo"; } funcOne ( ) { console.log(`first property is ${this.propOne}`) } } const newObj = new Name ( );
92
93
how to (list method/property and how to use) : - determine how many elements are in an array - add to / remove element from end of array - add to / remove element from beginning of array ///////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// other useful things to know (just list the name and generally how it works) : - determine whether something is an array or not - combine arrays without mutating — list 2 ways - check if an array contains a particular element or not (and how you know if the element is present or not) ///////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// - what does the slice & splice method do? -- describe syntax
part 1: length property --- arrayName.length *shorter-named method removes push method to add to end -- arrayName.push(element to be added) pop method to remove from end -- arrayName.pop ( ) *shorter-named method removes unshift method to add to beginning -- arrayName.unshift(element to be added) shift method to remove from end -- arrayName.shift ( ) part 2: Array.isArray (valueYouWantToCheck) firstArray.concat (secondArrayThatWillFollowTheFirst), spread operator arrayName.indexOf (elementYoureSearchingFor) -- returns index the element is at if its present, returns -1 otherwise (you can use this and as long as the returned value ISNT -1, you can assume the element is truly present in array) slice -- returns a COPIED portion of an iterable syntax : slice (inclusiveStart, exclusiveEnd) slice (inclusiveStart) — goes to the end of iterable slice( ) —- makes a copy of the entire thing splice -- mutates original array, returns an array containing modified contents (1) splice (1, 2, 3) 1 --- REQ'D inclusive index at which you want to start mutating array (if you add something, it will show up AT this index; if you delete something the element existing AT this index will be deleted) 2 --- OPTIONAL how many things to delete 3 --- items you'd like to insert (as many as you want separated by a comma) good link to discuss slice vs splice --- https://www.freecodecamp.org/news/lets-clear-up-the-confusion-around-the-slice-splice-split-methods-in-javascript-8ba3266c29ae/
94
what does the spread operator do, and when is it useful?
The spread operator expands or "spreads" an iterable (arrays, strings, objects) into separate arguments. this ==> console.log (...'hello') means this ==> 'h', 'e', 'l', 'l', 'o' //by using spread you have a list of separate arguments good reference article : https://medium.com/coding-at-dawn/how-to-use-the-spread-operator-in-javascript-b9e4a8b06fab You can : - COPY AN ARRAY OR OBJECT const fruits = ['🍏','🍊','🍌','🍉','🍍'] const moreFruits = [...fruits]; => could also be const moreFruits = {...fruits} if fruits were an OBJECT with properties console.log(moreFruits) // Array(5) [ "🍏", "🍊", "🍌", "🍉", "🍍" ] ^ ^ ^ ^ ^ REMEMBER : changes to the original array/object will NOT affect the copied array/object, which is what would happen if the array/object had been linked to the original with the assignment operator, = const array = ['😉','😊','😇'] const copyWithEquals = array // Changes to array will change copyWithEquals const copyWithSpread = [...array] // Changes to array will not change copyWithSpread array[0] = '😡' // Whoops, a bug console.log(...array) // 😡 😊 😇 console.log(...copyWithEquals) // 😡 😊 😇 console.log(...copyWithSpread) // 😉 😊 😇 ^ ^ ^ ^ ^ - COMBINE AN ARRAY OR OBJECT const hello = {hello: "😋😛😜🤪😝"} const world = {world: "🙂🙃😉😊😇🥰😍🤩!"} const helloWorld = {...hello,...world} console.log(helloWorld) // Object { hello: "😋😛😜🤪😝", world: "🙂🙃😉😊😇🥰😍🤩!" } const objectOne = {hello: "🤪"} const objectTwo = {world: "🐻"} const objectThree = {...objectOne, ...objectTwo, laugh: "😂"} // can ADD or replace existing key value pairs in the new object as well console.log(objectThree) // { hello: "🤪", world: "🐻", laugh: "😂" } const myArray = [`🤪`,`🐻`,`🎌`] const yourArray = [`🙂`,`🤗`,`🤩`] const ourArray = [...myArray,...yourArray] console.log(...ourArray) // 🤪 🐻 🎌 🙂 🤗 🤩 const objectFour = {...objectOne, ...objectTwo, laugh: () => {console.log("😂".repeat(5))}} objectFour.laugh() // 😂😂😂😂😂 ^ ^ ^ ^ ^ - WITH THE MATH FUNCTION, TO CONVERT THE ARGUMENTS INTO LIST VALUES const numbers = [37, -17, 7, 0] console.log(Math.min(numbers)) // NaN console.log(Math.min(...numbers)) // -17 console.log(Math.max(...numbers)) // 37
95
describe three ways to enumerate an object
1. for...in loop for (let nameRepresentingEachKey of objectName) { body }; 2. for...of loop with Object methods for (let [key, value] of Object.entries(objName)) *** for (let value of Object.values(objName)) *** for (let key of Object.keys(objName)) 3. array method with Object methods Object.keys(obj).forEach(key => { functionality }); *** remember that keys are automatically stored as strings when pulled from an object literal... if you need to act on or pass the numeric version of a key (if keys are numbers in the object), you have to convert the number (or variable holding the number) to a string value using parseInt function
96
filter array method : - describe params (within context of syntax), functionality / return - when is it best to use this method?
- params : arrName.filter ((element, index, array) => { }); - functionality / return : create a copy of a given array, filtered down with only the elements that return true when passed to the callbackFn test - great when : you have a conditional that you want to use to test multiple elements AND want an array returned
97
forEach array method : - describe params (within context of syntax), functionality / return - when is it best to use this method?
- params : arrName.forEach ((element, index, array) => { functionality WITH A RETURN OR PUSH STATEMENT }); - functionality / return : executes provided function once for each element - great for when : you don't need an array of values &/or your output is an object (you can build it & add values to it from an array) or a single primitive value that you can return out const nums = [9,8,7,6,5,4,3,2,1]; nums.forEach(function (n) { return n * n;} ) ; // prints: 81, 64, 49, 36, 25, 16, 4, 1 nums.forEach(function (el) { if (el % 2 === 0) {console.log(el)} }); // prints: 8, 6, 4, 2
98
map array method : - describe params (within context of syntax), functionality / return - when is it best to use this method?
- params : arrName.map ((element, index, array) => { functionality WITH A RETURN STATEMENT }); - functionality / return : create a copy of a given array with the results of invoking the callback on each element once AND return the array - great when : you want an array of evaluated results for your output
99
How would I create an array filled with the titles in this data structure? const movies = [ { title : 'Amadeus', score: 99 }, { title : 'Stand By Me', score: 85 }, { title : 'Alien', score: 90 } ] ;
const titles = movies.map (movie => movie.title);
100
how can you replace keys in an object? replace the key "add" with "newKey" while maintaining the order of the pairs : const testObj = { add : 1, bae : 2, cae : 3, dog : 4 }
const newObj = {newKey : 1, ...testObj}; delete newObj.add; console.log(newObj);
101
Array questions : 1. how can you create an array from an iterable? describe the method and the syntax! 2. how can you determine if a value is an array or not? 3. how to take an array & turn it into a string? describe the method and the syntax! 4. how to find the last instance / occurence of a value in an array? 5. how to flip the order of elements in an array?
1. (Array.from( ) method) Array.from( iterable or array-like object); ------- Takes any iterable (a Set, for example) or array-like object with a length property & indexed elements (a string) -- and creates an array from it Array.from('foo'); // [ "f", "o", "o" ] const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ] 2. (Array.isArray( ) method) Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false 3. (join ( ) method) arrayName.join (separator) -- creates and returns a string by concatenating all of the elements in the array & separating them by a commas w/ no spaces (default) or a specified separator const a = ['Wind', 'Water', 'Fire']; a.join(); // 'Wind,Water,Fire' a.join(', '); // 'Wind, Water, Fire' a.join(' + '); // 'Wind + Water + Fire' a.join(''); // 'WindWaterFire' 4. (lastIndexOf method) const numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); // -1 numbers.lastIndexOf(2, 3); // 3 numbers.lastIndexOf(2, 2); // 0 numbers.lastIndexOf(2, -2); // 0 numbers.lastIndexOf(2, -1); // 3 5. (reverse ( ) method) const items = [1, 2, 3]; console.log(items); // [1, 2, 3] items.reverse(); console.log(items); // [3, 2, 1]
102
how to take a string & turn it into an array? describe the method and the syntax, and a few ways to use this method /* let word = "THE HiSTory of mathematiCS"; convert word into an array, separating each word into separate elements. repeat, separating each letter into separate elements. */
split method let word = "THE HiSTory of mathematiCS"; word.split ( ); ======> empty parentheses gets one solid string, no matter how many words are in the string // ['THE HiSTory of mathematiCS'] word.split (" "); ======> quotations WITH A SPACE breaks up words into separate elements //['THE', 'HiSTory', 'of', 'mathematiCS'] word.split (""); ======> quotations WITHOUT SPACE breaks up words into separate letters // ['T', 'H', 'E', ' ', 'H', 'i', 'S', 'T', 'o', 'r', 'y', ' ', 'o', 'f', ' ', 'm', 'a', 't', 'h', 'e', 'm', 'a', 't', 'i', 'C', 'S']
103
how do you : iterate through an object? clone an object? gather all of the keys or values into an array? check for the existence of a property or method in an object?
for...in loop _____________________ Object.keys(objName) Object.values(objName) _____________________ object.assign OR spread operator const another = Object.assign({ color: yellow }, circle); const another = {…circle}; the assign method copies all of the key-value pairs in one or more source objects (circle), and pastes them into the target object ({ }) _____________________ in operator example : after creating/constructing some object, obj if ('keyName' in obj) console.log('keyName is in obj'); (https://codewithmosh.com/courses/310571/lectures/4881082)
104
WILL UPDATE, SKIP FOR NOW : describe how sort works, then complete these problems : https://coursework.vschool.io/array-sort-exercises/
if the callback returns a neg value, it sorts a before b; if it returns a positive value, it sorts b before a !! sort updates / mutates the original array by sorting values in place (alphabetical, highest num to lowest, or lowest num to highest) --- numeric sort is done using a compare callback function passed into the sort method const ascending = arrName.sort( (a,b) => a - b); (min to max number) const descending = arrName.sort( (a,b) => b - a); (max to min number) sort reference video : https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17010248#overview function leastToGreatest(arr) { return arr.sort((a,b) => a - b); } // console.log(leastToGreatest([1, 3, 5, 2, 90, 20])); // [1, 2, 3, 5, 20, 90] function greatestToLeast(arr) { return arr.sort((a,b) => b - a); } // console.log(greatestToLeast([1, 3, 5, 2, 90, 20])); // [90, 20, 5, 3, 2, 1] function lengthSort(arr) { return arr.sort((a, b) => a.length - b.length); } // console.log(lengthSort(["dog", "wolf", "by", "family", "eaten"])); // ["by", "dog", "wolf", "eaten", "family"] function alphabetical(arr) { return arr.sort(); } // console.log(alphabetical(["dog", "wolf", "by", "family", "eaten"])); // ["by", "dog", "eaten", "family", "wolf"] function byAge(arr){ return arr.sort((a,b) => a.age - b.age); } console.log(byAge([ { name: "Quiet Samurai", age: 22 }, { name: "Arrogant Ambassador", age: 100 }, { name: "Misunderstood Observer", age: 2 }, { name: "Unlucky Swami", age: 77 } ])); // => [ { name: 'Misunderstood Observer', age: 2 }, // { name: 'Quiet Samurai', age: 22 }, // { name: 'Unlucky Swami', age: 77 }, // { name: 'Arrogant Ambassador', age: 100 } ]
105
WILL UPDATE, SKIP FOR NOW what does array find & findIndex array methods do? why would you use find or findIndex vs filter? use find with to return the value with 5 letters, and use findIndex to return the first value with a 'u' : let cities = ["Ankara", "Istanbul", "Antalya", "Bursa", "Trabzon"];
find ( ) ---- iterate through an array until you find an item that satisfies the callback & return THAT ITEM. you can also pass in a function for more complicated searches SYNTAX : arrayName.find (callbackFn); example w/o a function : let cities = ["Ankara", "Istanbul", "Antalya", "Bursa", "Trabzon"]; let city = "Bursa"; let chars = 7; let match1 = cities.find(item => city === item ? true : null); console.log(`item from cities that matched was : ${match1}`); // should return 'item from cities that matched was : Bursa' let match2 = cities.find(item => chars === item.length); console.log('item with matching length at position', match2); // let match2 = cities.find(item => chars === item.length); _______________________________________________________________ findIndex ( ) ---- iterate through an array, look for a matching item & return the POSITION SYNTAX : arrayName.find (callbackFn); let cities = ["A'Tnkara", "Istanbul", "Antalya", "Bursa", "Trabzon"]; let index = cities.findIndex(item => item.toLowerCase().indexOf("t") > -1); console.log(`Letter 't' found in item at index ${index}`); // 'Letter 't' found in item at index 0' let word = cities.find(item => item.toLowerCase().indexOf("t") > -1); console.log(`word found : ${word}`); //'Letter 'T' found in item at index AnkaTra' /* */* */* */* */* */* */* */* */* */* */* */* */* */* */* */ filter is helpful for testing multiple values & returning an array, versus a single value reference video : https://www.youtube.com/watch?v=9b6gxQZHvis
106
WILL UPDATE, SKIP FOR NOW generally describe what these array methods do (syntax, functionality, return value) : - flat - every - some 1. flatten this array to a single level 2. determine if every value has seven characters - use method and predict outcome 3. determine if some values have the letter a - use method and predict outcome let cities = [["Ankara", "Istanbul"], ["Antalya", ["Bursa", "Trabzon"]]];
- arrName.flat ( depth(optional) ) --- functionality / return : creates a new array with the sub-array elements concatenated into it up to the specified depth - arrName.every ( conditionalCallbackFn ) --- functionality : test if every element in the array pass the callback test; return : boolean value - arrName.some ( conditionalCallbackFn ) --- functionality : test if at least one element in the array passes the test; return : boolean value console.log(cities.flat(3).some(el => el.length === 9));
107
Array Methods (name the method AND what it returns) : - add to the end - add to the beginning - remove from the beginning - remove from the end
PUSH - adds element(s) to end + returns the new length of array UNSHIFT - add element(s) to beginning + returns new length of array SHIFT - remove element beginning + returns removed element POP - remove element from end + returns the removed value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
108
Array Methods (name the method AND what it returns) : - merge arrays - look for a value (two methods) - create a string from array - flip the order
CONCAT - merge multiple (as many as you want) arrays (arr1.concat(arr2)) + returns a new array with the elements in first array followed by elements in the second array INCLUDES - look for a value + return true (if arg is present in array) or false (if not present) syntax : includes(searchElement, optionalStartingIndexToSearchFrom) + INDEXOF (indexOf) - look for value + return index where val is located or -1 if the val isn’t present syntax : indexOf(searchElement, optionalStartingIndexToSearchFrom) ——> includes to check if something is present but don’t need to know where, indexOf if you n eed the location JOIN - concats elements in array into one string, separated by commas (default if no arg is passed in) or specified separator syntax : let letters = [ 'T', 'C', 'E', 'P', 'S', 'E', 'R' ]; let song = letters.reverse().join('.'); //"R.E.S.P.E.C.T" REVERSE - mutates array by reversing the array in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array