Javascript Flashcards
What are objects used for?
In JavaScript, an object is a standalone entity, with properties and type. An object is a collection of related data and/or functionality. Objects can be used for data models
What are object properties?
A property of an object can be explained as a variable that is attached to the object. The properties of an object define the characteristics of the object.
Describe object literal notation.
opening and closing curly brace
How do you remove a property from an object?
delete operator followed by object.property
What are the two ways to get or update the value of a property?
bracket or dot notation: object.property or object[property]
What is the purpose of variables?
To store values to the variable so we can reuse it
How do you declare a variable?
var keyword variableName
How do you initialize (assign a value to) a variable?
= (assignment operator) valueOfVariable (on right of variable declaration)
What characters are allowed in variable names?
numbers, letters, $, period, underscore
What does it mean to say that variable names are “case sensitive”?
Variable names must be cased consistently
What is the purpose of a string?
To be used with text
What is the purpose of a number?
To be used with calculations, to store numerical values
What is the purpose of a boolean?
On/off switch. To determine to run script or not. Useful when code has multiple paths
What does the = operator mean in JavaScript?
Assigment operator, assigns value to variable
How do you update the value of a variable?
variableName = newValue;
What is the difference between null and undefined?
Null- intentional absence of value by user
Undefined- value does not exist according to computer
Why is it a good habit to include “labels” when you log values to the browser console?
Gives value context and indicates what that value is
Give five examples of JavaScript primitives.
string, number, boolean, undefined, null
What data type is returned by an arithmetic operation?
number
What is string concatenation?
Joining strings end to end with + operator
What purpose(s) does the + plus operator serve in JavaScript?
Addition and concatenation
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
The += operator adds the value on its right to the variable or property on its left, and assigns the result to the variable or property on its left
What are arrays used for?
To store a collection of data
Describe array literal notation.
var variableName = [];
How are arrays different from “plain” objects?
Objects contain properties related to the object and functions (methods).
Arrays are a collection of data
What number represents the first index of an array?
0
What is the length property of an array?
The length property of an object which is an instance of type Array, sets or returns the number of elements in that array
How do you calculate the last index of an array?
subtract 1 for the value returned from array.length
What is a function in JavaScript?
A set of statements that performs a task or calculates a value. Takes some input (arguments) and returns an output
Describe the parts of a function definition.
function keyword, optional function name, parameters, curly braces for code block, return statement
Describe the parts of a function call.
functionName(arguments)
When comparing them side-by-side, what are the differences between a function call and a function definition?
In a function call, the function is being executed and arguments are passed into the parameter field to return an output. In a function definition, no output is being generated and the function keyword is used to define the function and there is a code block of statements
What is the difference between a parameter and an argument?
Arguments are the values being passed into parameters. Parameters are like placeholders
Why are function parameters useful?
They let you know how many inputs are required and depending on the name, the context of the values that should be passed into the function
What two effects does a return statement have on the behavior of a function?
To end the function and to generate an output/result
Why do we log things to the console?
To check the output of our functions/methods
What is a method?
A method is a programmed procedure that is defined as part of a class and included in any object of that class. A function defined within an object
How is a method different from any other function?
A method and function are both a set of instructions. A method is associated with an object while a function is not. Example: the push method is associated with array literals but not strings.
How do you remove the last element from an array?
array.pop();
How do you round a number down to the nearest integer?
Math.floor();
How do you generate a random number?
Math.random()
How do you delete an element from an array?
array.splice(index of unwanted element, #of elements you want removed starting from that index)
How do you append an element to an array?
array. push()
array. unshift()
How do you break a string up into an array?
string.split(delimiter/pattern you want the string split at);
ex: var str = “Crocodiles are super scary”
var array = str.split(“ “); //splits at every space
array = [Crocodiles, are, super, scary]
Do string methods change the original string? How would you check if you weren’t sure?
No they do not change the original string. Strings are immutable, cannot be added onto or deleted. We can check by console logging the original string
Roughly how many string methods are there according to the MDN Web docs?
~50
Is the return value of a function or method useful in every situation?
no. They’re useful when the situation has a need for it. Ex. In financial calculations dealing with dollars and cents, calling the math.floor() function would lead to a lot of inaccuracies
Roughly how many array methods are there according to the MDN Web docs?
~40
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Give 6 examples of comparison operators.
!== > < >= <= ===
What data type do comparison expressions evaluate to?
boolean data type
What is the purpose of an if statement?
It is for decision-making for guiding the program to follow a certain path depending on whether a condition has been met or not
Is else required in order to use an if statement?
No, if the condition is not met, you will naturally be exited out of the if-statement
Describe the syntax (structure) of an if statement.
keyword if (condition) { code block }
What are the three logical operators?
&& and (returns true if all anded values are also true)
|| or (returns true if at lease one or-ed value is true)
! not
How do you compare two different expressions in the same condition?
put each expression in set of parenthesis
What is the purpose of a loop?
Loops allow you to repeat a process over and over without having to write the same (potentially long) instructions each time you want your program to perform a task
What is the purpose of a condition expression in a loop?
the condition of a loop marks a stopping point.
What does “iteration” mean in the context of loops?
One iterations is one completed loop, one run-through of the code
When does the condition expression of a while loop get evaluated?
In the beginning, before each iteration
When does the initialization expression of a for loop get evaluated?
When the loop starts, before anything else. One time
When does the condition expression of a for loop get evaluated?
Every time the loop runs. Before the code block inside the loop is executed. Before each time the loop iterates
When does the final expression of a for loop get evaluated?
Each time after the code block is executed. After each iteration of the loop, before the condition is checked
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
break
What does the ++ increment operator do?
It increments the value of the variable by one. Reassigns, substitutes the value in place of the original value
How do you iterate through the keys of an object?
For In loop.
For (var x in object) {code block}
Why do we log things to the console?
To check for errors, to make sure our functions and code is returning the desired values
What is a “model”?
A model is called a DOM tree and it is stored in the browsers’ memory. Models are made of objects and nodes
Which “document” is being referred to in the phrase Document Object Model?
the HTML page
What is the word “object” referring to in the phrase Document Object Model?
the datatype object
What is a DOM Tree?
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.
Give two examples of document methods that retrieve a single element from the DOM.
getElementById()
querySelector()
Give one example of a document method that retrieves multiple elements from the DOM at once.
getElementsByClassName()
querySelectorAll()
Why might you want to assign the return value of a DOM query to a variable?
You might need to access an element more than once. It’s more efficient to store a value in a variable because the browser doesn’t need to look through the DOM tree to find the same element again
What console method allows you to inspect the properties of a DOM element object?
console.dir();
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
The browser needs to load all the HTML and CSS before the JavaScript code can access them
What does document.querySelector() take as its argument and what does it return?
a css selector in between quotes. It returns only the first of the matching elements
What does document.querySelectorAll() take as its argument and what does it return?
a css selector in between quotes. It returns all the element that have that match.
What is the purpose of events and event handling?
To trigger a particular function, for greater user interactivity with the web application
Are all possible parameters required to use a JavaScript method or function?
no
What method of element objects lets you set up a function to be called when a specific type of event occurs?
addEventListener
What is a callback function?
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
What object is passed into an event listener callback when the event fires?
event object with all data about whatever occurred/describes the event
What is the event.target? If you weren’t sure, how would you check? Where could you get more information about it?
The element the event happened on.
The element node that is being checked for the occurrence of an event.
console log event.target
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick())
When a function has no arguments, it does not receive any data from the calling function
What is the className property of element objects?
The className property of the Element interface gets and sets the value of the class attribute of the specified element
How do you update the CSS class attribute of an element using JavaScript?
document.querySelector(‘name’)
elementNodeReference.className = ‘.class-name’;
What is the textContent property of element objects?
The textContent property of the Node interface represents all the text content of the node and its descendants.
How do you update the text within an element using JavaScript?
query for element
elementNode.textContent = ‘text’;
Is the event parameter of an event listener callback always useful?
No. Ex: call back function argument in addEventListener method
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
more complicated. Javascript functionality should be reliant on data stored in javascript
Why is storing information about a program in variables better than only storing it in the DOM?
for later reuse, to reference back to the values stored in the variables. For efficiency
What does the transform property do?
The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.
Give four examples of CSS transform functions.
translateY, rotate, skew, scale
What event is fired when a user places their cursor in a form control?
focus event
What event is fired when a user’s cursor leaves a form control?
Blur event
What event is fired when a user’s cursor leaves a form control?
input event
What event is fired when a user clicks the “submit” button within a ?
submit event
What does the event.preventDefault() method do?
The preventDefault() prevents the default action of an event
What does submitting a form without event.preventDefault() do?
It makes the form values clear from the fields?
What property of a form element object contains all of the form’s controls.
elements property
What property of a form control object gets and sets its value?
value property
What is one risk of writing a lot of code without checking to see if it works so far?
You have no idea at what point in the code things went wrong. You don’t know what the values are in essential variables.
What is an advantage of having your console open when writing a JavaScript program?
You can see what is happening at any line of code. You can see whether your code is doing what it’s supposed to be doing each step of the way.
Does the document.createElement() method insert a new element into the page?
No, it creates an element node in the dom tree. It creates a javascript object but it is not visible in the html page.
How do you add an element as a child to another element?
parentElement.appendChild(childElement);
What do you pass as the arguments to the element.setAttribute() method?
setAttribute(‘attributeName’, ‘attributeValue’)
What steps do you need to take in order to insert a new element into the page?
var someEl = document.createElement(‘element’);
var elText = document.createTextNode(‘text’);
someEl.appendChild(elText);
find the parent (querySelector(‘parentEl’);
parentEl. appendChild(someEl);
What is the textContent property of an element object for?
The textContent property of the Node interface represents the text content of the node and its descendants. It is useful when you only want to change the content of an already existing element. To get and set text content
Name two ways to set the class attribute of a DOM element.
className property, setAttribute() method
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
You can test the function easily and pass values into to see the output. Reuse the code easily.
What is a method
a special kind of property that has a function
The transition property is shorthand for which four CSS properties?
transition-delay - how long to wait to start transition
transition-duration - how long the animation time is
transition-property - sets the CSS properties to which a transition effect should be applied.
transition-timing-function - sets how intermediate values are calculated for CSS properties being affected by a transition effect (ease-in steps)
What is the event.target?
The element the event happened on
Why is it possible to listen for events on one element that actually happen its descendent elements?
Event flow- the order in which the events fire.
Event bubbling: the event starts at the most specific node and flows outwards to the least specific one
What DOM element property tells you what type of element it is?
event.target.tagName
What does the element.closest() method take as its argument and what does it return?
It takes in the desire selector string. It finds the closest ancestor node that matches the selector string
How can you remove an element from the DOM?
elementNode.remove();
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?
wrap the clickable element in a parent element. Put the listener on the parent element. Whenever the child is clicked, the listener on the parent will recognize that event. Event delegation
What is the event.target?
The element that triggered the event
What is the affect of setting an element to display: none?
Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist), removed from document flow. All descendant elements also have their display turned off.
What does the element.matches() method take as an argument and what does it return?
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. The argument is the selector string. The return is a boolean
How can you retrieve the value of an element’s attribute?
element.getAttribute(attributeName)
At what steps of the solution would it be helpful to log things to the console?
Every step
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?
createElement(), add textContent, appendChild, className
you would have to addEventListener to each element
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?
You would set a condition for every “view”. You’d get the view’s index and check if it was either ‘css’, ‘html’, or ‘javascript’ and change the classes if it happened to meet the specified value.
What is JSON?
JSON is a text-based data format following JavaScript object syntax
JavaScript object notation
What are serialization and deserialization?
Serialization is the process of turning an object in memory into a stream of bytes so you can do stuff like store it on disk or send it over the network.
Deserialization is the reverse process: turning a stream of bytes into an object in memory.
Why are serialization and deserialization useful?
Transfer things across the network and save to harddrive
How do you serialize a data structure into a JSON string using JavaScript?
You write your code following JSON structure (quotes). JSON.stringify()
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse()
How to you store data in localStorage?
localStorage.setItem(‘key’, ‘keyValue’);
How to you retrieve data from localStorage?
localStorage.getItem(‘key’);