Javascript p2 Flashcards

DOM querying +

1
Q

What is the DOM?

A

Document Object Model

    • DOM is an API (Application Programming Interface), a UI/means by which programs and scripts talk to each other.
    • The DOM states what your script can ask the browser about the current page, and how to tell the browser to update what is being shown.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why do we log things to the console?

A

– to get feedback, learn what is where so we can manipulate it

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

What is a “model”?

A

– a replication, example, representation

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

Which “document” is being referred to in the phrase Document Object Model?

A

– the website in question

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

What is the word “object” referring to in the phrase Document Object Model?

A
    • the model is made of objects, an object-model of the document
    • each object represents a different part of the page loaded in the browser
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a DOM Tree?

A
    • a model of a web page

- - document nodes, elements nodes, attribute nodes, text nodes

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

Give two examples of document methods that retrieve a single element from the DOM.

A
    • getElementById(‘id’), uses value of an elements ID attribute, which should be unique on the page
    • querySelector(‘css selector’), returns first matching element
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Give one example of a document method that retrieves multiple elements from the DOM at once.

A
    • getElementsByClassName(), grabs all elements of a class
    • getElementsByTagName(), grabs all elements of a tag name
    • querySelectorAll(), grabs all elements of a CSS selector
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why might you want to assign the return value of a DOM query to a variable?

A
    • cache a thing when you need to work with it more than once
    • this stores a reference to where the node is, not the element itself but directions to it
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What console method allows you to inspect the properties of a DOM element object?

A

– console.dir()

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

Why would a script> tag need to be placed at the bottom of the HTML content instead of at the top?

A

–the browser needs to parse all the elements in the HTML before the JS code can access them

(sneaky:
script js.link defer script
defer will cache the code to run after page loads so link can go in head)

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

What does document.querySelector() take as its argument and what does it return?

A

– takes a CSS selector and returns the first matching element

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

What does document.querySelectorAll() take as its argument and what does it return?

A

– takes a CSS selector and returns a node list of all elements which use it

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

node list vs array?

A
  • a NODE LIST is not an ARRAY. it just sort of looks and acts like one
  • they are numerically indexed objects that look like arrays
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why do we log things to the console?

A

– to get feedback, learn what is where so we can manipulate it

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

What is the purpose of events and event handling?

A
    • to make the site feel more interactive

- - by causing responses to various prompts

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

Are all possible parameters required to use a JavaScript method or function?

A

– no. not all methods require all parameters set, some are optional

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

What method of element objects lets you set up a function to be called when a specific type of event occurs?

A

– .addEventListener(‘event’, function, optional)

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

What is a callback function?

A

– a function we give to another function
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

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

What object is passed into an event listener callback when the event fires?

A

– the event object, passed in by the element

callBackFunction(event) { }

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

What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?

A
    • the target property will store the element that was interacted with
    • console.log()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the difference between these two snippets of code?

1) element.addEventListener(‘click’, handleClick)
2) element.addEventListener(‘click’, handleClick())

A

1) element.addEventListener(‘click’, handleClick)
- - this one would run handleClick when the click event fires
- - a callback function

2) element.addEventListener(‘click’, handleClick())
- - this will pass the return of handleClick() as the argument, not the function itself
- - this one would run handleClick as the page loads, rather then on event fire

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

What is the className property of element objects?

A

– the classes assigned to that element

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

How do you update the CSS class attribute of an element using JavaScript?

A

– el.className = ‘all class names to apply’

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

What is the textContent property of element objects?

A

– allows you to access the text content in the element

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

How do you update the text within an element using JavaScript?

A

– el.textContent = ‘new text’ or other variable value

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

Is the event parameter of an event listener callback always useful?

A

– not always

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

Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?

A

– more complicated

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

Why is storing information about a program in variables better than only storing it in the DOM?

A

– quicker, easier to manipulate

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

What event is fired when a user places their cursor in a form control?

A

– focus

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

What event is fired when a user’s cursor leaves a form control?

A

– blur

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

What event is fired as a user changes the value of a form control?

A

– change

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

What event is fired when a user clicks the “submit” button within a form?

A

– submit event

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

What does the event.preventDefault() method do?

A
    • prevent the browser from automatically reloading the page with the form’s values in the URL.
    • prevent refresh of page & submission to URL
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What does submitting a form without event.preventDefault() do?

A

– allows refresh of page and submission to URL

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

What property of a form element object contains all of the form’s controls?

A

– HTMLFormElement
– nodeList = HTMLFormElement.elements
The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the element

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

What property of a form control object gets and sets its value?

A

– value

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

What is one risk of writing a lot of code without checking to see if it works so far?

A
    • many errors, no context

- - loss of specificity

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

What is an advantage of having your console open when writing a JavaScript program?

A

– immediate feedback

40
Q

remember there are two kinds of functions:

A
    • ones that return info (void)

- - ones that change things (mutator)

41
Q

Does the document.createElement() method insert a new element into the page?

A

– not until you call .appendChild() with it, it only creates the element you can add

42
Q

How do you add an element as a child to another element?

A
    • node.appendChild(child);

- - will add to end of list

43
Q

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
This means that a node can’t be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position. The Node.cloneNode() method can be used to make a copy of the node before appending it under the new parent.

A
    • list.insertBefore(child, target); (where target is other child to insert before)
    • to add to start of list
44
Q

What do you pass as the arguments to the element.setAttribute() method?

A
    • the name of the attribute whose value is to be set
    • the value to assign to the attribute
    • element.setAttribute(attName, value);
45
Q

What steps do you need to take in order to insert a new element into the page?

A
  1. var x = doc.createElement(‘el’) - creates & stores in variable
  2. var y = doc.createTextNode(‘copy’) - optional, provides content for new element
  3. x.appendChild(y) - adds content to element
  4. parent.appendChild(x) - adds element to the page/parent

create: var newEl = document.createElement(‘type to create’);
create: var newText = document.createTextNode(‘text goes here’);
attach: newEl.appendChild(newText);
find loc: var position = document.getElementByTagName(‘tag’)[#];
insert: position.appendChild(newEl);

46
Q

What is the textContent property of an element object for?

A

– get or set text content for an element

The textContent property of the Node interface represents the text content of the node and its descendants.

47
Q

Name two ways to set the class attribute of a DOM element.

A
    • setAttribute();

- - .className =

48
Q

What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?

A
    • automate repetitive work
    • can be reused
    • can change it anytime
49
Q

What is the event.target?

A

– the element from which the event originated

The target of the event (most specific element interacted with)

50
Q

Why is it possible to listen for events on one element that actually happen its descendent elements?

A

– event bubbling

51
Q

What DOM element property tells you what type of element it is?

A

– tagName

52
Q

What does the element.closest() method take as its argument and what does it return?

A

– it takes an element name and returns the closest of that element to the calling element

el01.closest(el02) == closest el02 to el01

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

53
Q

How can you remove an element from the DOM?

A

– element.remove();

The Element.remove() method removes the element from the tree it belongs to.

54
Q

If you wanted to insert new clickable DOM elements into the page using JavaScript, how could you avoid adding an event listener to every new element individually?

A

– by adding one to the parent, and using bubbling event to catch it

55
Q

3 parts of adding an event listener:

A
  • callback function
  • var $element = doc.querySelector(‘element’);
  • $element.addEventListener(‘event’, callBack);
56
Q

what’s a Logic Gate?

A
  • a check to exit a function if condition not met
57
Q

talk about node lists:

A

nodeLists can be looped through even though they aren’t arrays

NodeList objects are collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll().
Although NodeList is not an Array, it is possible to iterate over it with forEach() or a for loop (but not for…in). It can also be converted to a real Array using Array.from().

58
Q

What is the event.target?

A

– the element from which the event originated
The target of the event (most specific element interacted with)

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {

// e.target is the clicked element!

// If it was a list item
	if(e.target && e.target.nodeName == "LI") {
// List item found!  Output the ID!
console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
	}
});
59
Q

What is the effect of setting an element to display: none?

A

– removes the element from the flow of the doc

60
Q

What does the element.matches() method take as an argument and what does it return?

A

– it takes a selector string and returns a boolean saying if that string matches the element

The matches() method checks to see if the Element would be selected by the provided selectorString – in other words – checks if the element “is” the selector.

var result = element.matches(‘.selectorString’);

61
Q

How can you retrieve the value of an element’s attribute?

A

– with .getAttribute()

The getAttribute() method of the Element interface returns the VALUE of a specified attribute on the element.

let attribute = element.getAttribute(attributeName);

62
Q

At what steps of the solution would it be helpful to log things to the console?

A

– any step that assigns or returns values

63
Q

If you were to add another tab and view to your HTML, but you didn’t use event delegation, how would your JavaScript code be written instead?

A

– more listeners and callback functions

64
Q

If you didn’t use a loop to conditionally show or hide the views in the page, how would your JavaScript code be written instead?

A

– many if/else statements

65
Q

What is JSON?

A

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.

66
Q

What are serialization and deserialization?

A

– serialization: converting native object into string
– deserialization: converting string to a native object
Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.

67
Q

Why are serialization and deserialization useful?

A

– you can pack up objects into a relatively small bundle (of bytes, a bit sequence) to transfer or store them in memory, then unpack them later without any loss

Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications

68
Q

How do you serialize a data structure into a JSON string using JavaScript?

A
-- JSON.stringify()
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
69
Q

How do you deserialize a JSON string into a data structure using JavaScript?

A

–JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
JSON.parse(text)
JSON.parse(text, reviver)

70
Q

How to you store data in localStorage?

A
    • .setItem()

- - localStorage.setItem(keyName, keyValue);

71
Q

How to you retrieve data from localStorage?

A
    • .getitem()

- - var aValue = localStorage.getItem(keyName);

72
Q

What data type can localStorage save in the browser?

A

– JSON string data

73
Q

When does the ‘beforeunload’ event fire on the window object?

A

– when the window, the document, and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

74
Q

What is a method?

A

A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.

75
Q

How can you tell the difference between a method definition and a method call?

A
    • a def will have a codeblock following it, creating what it does
    • a call would be: object.method(); (dot notation)
76
Q

Describe method definition syntax (structure).

A

person.name = function () {
return this.firstName + “ “ + this.lastName;
};

const obj = {
foo() {
// …
},
bar() {
// …
}
}

77
Q

Describe method call syntax (structure).

A
    • object.method

- - object.method();

78
Q

How is a method different from any other function?

A

– it’s a part of an object

79
Q

What is the defining characteristic of Object-Oriented Programming?

A

objects can contain both data (as properties) and behavior (as methods)

80
Q

What are the four “principles” of Object-Oriented Programming?

A
    • abstraction
    • encapsulation
    • inheritance
    • polymorphism
81
Q

What is “abstraction”?

A

being able to work with (possibly) complex things in simple ways

82
Q

What does API stand for?

A
    • application programming interface

- - a connection between computers so they or their programs can interact

83
Q

What is the purpose of an API?

A

– to give programmers a way to interact with a system in a simplified, consistent fashion (an abstraction)

84
Q

What is this in JavaScript?

A

– a self-referential parameter ?
– a contextual parameter ?

A better question to ask is “When is this?”

By default, when you call a function, it’s this will be given the value of the global window object.

85
Q

What does it mean to say that this is an “implicit parameter”?

A

it means that it (this) is available in a function’s code block even though it was never assigned in the function’s parameter list or declared with var

    • which is to say, it is not explicitly defined, but instead implicitly available
    • it does not need to be explicitly defined
86
Q

When is the value of this determined in a function; call time or definition time?

A

– call time. the value of this is determined when the function is called, not defined.

87
Q
What does this refer to in the following code snippet?
var character = {
  firstName: 'Mario',
  greet: function () {
    var message = 'It\'s-a-me, ' + this.firstName + '!';
    console.log(message);
  }
};
A

– the value of the firstName property of THIS object, var character

88
Q
var character = {
  firstName: 'Mario',
  greet: function () {
    var message = 'It\'s-a-me, ' + this.firstName + '!';
    console.log(message);
  }
};

Given the above character object, what is the result of the following code snippet? Why?
character.greet();

A
    • it would return: ‘It’s-a-me, Mario!’
    • bc character is the object which contains the method ‘greet’, which refers to the firstName property of character in its codeblock
89
Q
var character = {
  firstName: 'Mario',
  greet: function () {
    var message = 'It\'s-a-me, ' + this.firstName + '!';
    console.log(message);
  }
};
Given the above character object, what is the result of the following code snippet? Why?
var hello = character.greet;
hello();
A
    • undefined
    • it’s being called on the default global scope (the window), not the specific obj
- var hello = character.greet;
hello();
- what character? greet() refs 'this' inside the character obj, so it won't work outside in global
90
Q

How can you tell what the value of this will be for a particular function or method definition?

A
    • no way to know for sure

- - it’ll be referring to the properties of the object it’s within ?

91
Q

How can you tell what the value of this is for a particular function or method call?

A

– the dot notation will tell you/it which object it’s referring to
– the lexical scope of the call

Find where the function is called and look for an object to the left of the dot. If you can’t see where the function (or method) is called, then you cannot say for sure what the value of this is.

92
Q

This list is not comprehensive, but if you remember the following rules, you should be able to understand code that utilizes this in simple scenarios:

A
  • this is an implicit parameter of all JavaScript functions.
  • the value of this is determined at call time.
  • the value of this can be recognized as “the object to the left of the dot” when the function is called (as a method).
  • if there is no value to the left of the dot when the function is called, then by default, this will be the global window object.
  • if you cannot see the function being called, then you do not know what the value of this will be.
93
Q

By default, when you call a function, it’s this will be given the value of the global window object.

(answer is example)

A
function thisIsWindow() {
  if (this === window) {
    return 'yep'
  } else {
    return 'nope'
  }
}

thisIsWindow(); // “yep”

var pet = {
  type: 'doggo',
  rating: 12
};

pet. thisIsWindow = thisIsWindow;
pet. thisIsWindow(); // “nope”

94
Q

What kind of inheritance does the JavaScript programming language use?

A

– prototypal, or prototype-based

95
Q

What is a prototype in JavaScript?

A
    • template from which objects draw their abilities (methods/functions, etc)
    • an object which has some functionality that would be applied to any object created out of it
96
Q

How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on objects, arrays, and numbers?

A
    • bc they exist on their associated prototype
  • -
    objec. setPrototypeOf(obj, prototype);
97
Q

If an object does not have it’s own property or method by a given key, where does JavaScript look for it?

A

– on the prototype