JavaScript Flashcards
What is the purpose of variables?
Variables store data
How do you declare a variable?
Use the keyword var to create a variable and give it a name. Statement ends with a semicolon.
EX: var firstName;
How do you initialize (assign a value to) a variable?
Use the var key word to initialize a new variable. Use the = assignment operator to give the variable a value.
EX: var firstName = ‘Rachel’
What characters are allowed in variable names?
letters, numbers, dollar sign ($), or underscore (_).
What does it mean to say that variable names are “case sensitive”?
Use of capital and lower cases are important in the variable name. score and Score would be 2 different variables, but it is bad practice to create two variables that have the same name using different cases.
What is the purpose of a string?
The strings data type consists of letters and other characters. Strings are useful when working with any kind of text.
What is the purpose of a number?
The numeric data type handles numbers.
For tasks that involve counting or calculating sums, you will use numbers 0-9.
What is the purpose of a boolean?
Boolean data types can have one of two values: true or false. Booleans are helpful when determining which part of a script should run.
what does the = operator mean in JavaScript?
the equals sign (=) is an assignment operator. It says that you are going to assign a value to the variable/ update the value given to a variable.
How do you update the value of a variable?
variableName = newValue
What is the difference between null and undefined?
Null means nothing, undefined means the value has not been set/assigned yet.
Why is it a good habit to include “labels” when you log values to the browser console?
A console log “label” is a short string that describes the variable or value being logged.
Give 5 examples of JavaScript primitives.
String, number, boolean, undefined, null.
What data type is returned by and arithmetic operation?
Number
What is string concatenation?
Joining of 2 or more strings by using + operator
what purpose(s) does the + operator serve in JavaScript?
Arithmetic addition, concatenating strings
what data type is returned by comparing two values ( < , > , = = = , etc)?
boolean - true or false
What does the += “plus-equals” operator do?
addition assignment
What are objects used for?
Objects are used to group together a set of variables and functions. Used to group related data together.
what are object properties?
Properties tell us about the object. Property is a key-value pair.
Describe object literal notation.
var objectName = {
property: value,
property: value,
};
How do you remove a property from an object?
Using the delete operator followed by objectName.propertyName OR objectName[“propertyName”]
What are the two ways to get or update the value of a property?
.notation OR
[“bracket notation”]. .notation is preferable for objects.
Bracket notation is used when the property name is not actually known (it’s in a variable or i needs o be calculated. Bracket notation is also required when the property key is not a valid identifier (variable name)
What are arrays used for?
To store a list or set of values that are related to each other in one variable.
Describe array literal notation.
var arrayName = [‘item 1’ , ‘item 2’ , ‘item 3’];
How are arrays different from ‘plain’ objects?
Items in an array are in a numbered list. Each item in the array is automatically given a number called and index. Objects can have named properties for the values but arrays are numbered.
What number represents the first index of an array?
0 - computers start counting from 0, 1, 2, 3 etc.
What is the length property of an array?
The length property holds the number of items in the array.
How do you calculate the last index of an array?
lastIndex = arrayName.length - 1
What is a function in Javascript?
A group of steps/actions that are stored.
Describe the parts of a function definition.
function keyword, optional function name, optional parameters, opening curly brace, block of code to be executed when function is called. within the code block should be a return statement - closing curly brace.
Describe the parts of a function call.
Name of the function followed by ( ) with any arguments (if any) passed included in the parenthesis. Ending with semicolon.
When comparing them side-by-side, what are the differences between a function call and a function definition?
Function definition contains curly braces indicating a block of code to be executed. Function definition will also include the function keyword where the call does not.
What is the difference between a parameter and an argument?
Parameters variables without a value, the arguments is the value for that parameter.
Why are function parameters useful?
Parameters give us the ability to add in variance (mutability). Result can now vary based on the information thats passed in.
What two effects does a return statement have on the behavior of a function?
- Causes the function to produce a value we can use in our program.
- Prevents any more code in the function’s code block from being run.
Why do we log things to the console?
console.log is a debugging tool geared towards development To check the output of your code and see if any errors occur
What is a method?
A method is a function which is a property of an object.
How is a method different from any other function?
Methods are called on a variable/object. Syntax is the main difference.
How do you remove the last element from an array?
pop( ) method.
How do you round a number down to the nearest integer?
Math.floor ( ) - floor method of the Math object.
How do you generate a random number?
Math.random ( ) - random method of the Math object. Range is between 0-1 not inclusive of 1. Then you can multiply that decimal by the maximum or minimum value you need to get a the range you want.
How do you delete an element from an array?
splice( ) method.
How do you append an element to an array?
push ( ) method.
How do you break a string up into an array?
split ( ) method.
Do string methods change the original string? How would you check if you weren’t sure?
Strings are not mutable so the original string can’t be changed. You can check by looking at documentation @ MDN / you can try it yourself in the console to see the outcome.
Roughly how many string methods are there according to the MDN Web docs?
Roughly 50 different methods / check for them on MDN
Is the return value of a function or method useful in every situation?
Sometimes the return is not necessary - but a return is always there if you need it. If you need the return later you can save the return in a variable
Roughly how many array methods are there according to the MDN Web docs?
Roughly 40 different methods / check for them on MDN
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 - true or false
What is the purpose of an if statement?
the if statement evaluates (or checks) a condition. if the condition evaluates to be truthy, any statements in the subsequent code block are executed.
Is else required in order to use an if statement?
An else statement is not required to use an if statement. Else is a fallback statement.
Describe the syntax (structure) of an if statement.
if (condition) { //code to be executed if condition is truthy}
What are the three logical operators?
& & ; - logical and, | | - logical or, ! - logical not
How do you compare two different expressions in the same condition?
wrap each individual expression in parenthesis and wrap the whole condition in a set of parenthesis.
EX. if ( (score1 + score2) > (highScore1 + highScore2) ) { //code to execute }
What is the purpose of a loop?
To execute/repeat a code block any number of times.
What is the purpose of a condition? (in reference to loops)
A condition specifies the amount of times a code block should execute. If the condition is truthy the code block will run. When the condition is false the loop ends.
What does “iteration” mean in the context of loops?
round - or pass through the loop.
When does the condition expression of a while loop get evaluated?
Before each pass through the loop.
When does the initialization expression of a for loop get evaluated?
Initialization expression is evaluated once before the loop begins.
When does the condition expression of a for loop get evaluated?
Condition expression is evaluated after initialization is evaluated and before each loop iteration (round).
When does the final expression of a for loop get evaluated?
The final expression is evaluated at the end of each loop iteration (round).
Besides a return statement, which exits its entire function block, which keyword exits a loop before its condition expression evaluates to false?
Break keyword
What does the ++ increment operator do?
The increment operator (++) increments (adds one to) its operand AND returns a value.
How do you iterate through the keys of an object?
Using a for . . . in loop
What is a “model”?
A system or thing used as an example to follow or imitate
Which “document” is being referred to in the phrase Document Object Model
The browsers interpretation of the HTML document. Object refers to JavaScript objects
What is a DOM Tree?
A model of a web page (or portion of the page) consisting of all elements and their nodes from the most parental element downwards.
Give 2 examples of document methods that retrieve a single element from the DOM?
.getElementById( );
.querySelector( );
Give 1 example of a document method that retrieves multiple elements from the DOM.
.querySelectorAll( );
.getElementByClassName( );
.getElementByTagName( );
When might you want to assign the return value of a DOM query to a variable?
If your script needs to use the same element(s) more than once, you can store the location of the element(s) in a variable.
What console method allows you to inspect the properties of a DOM element object?
console.dir( );
Why would a < script > tag need to be placed at the bottom of the HTML content instead of at the top?
Because the browser needs to parse all the of the elements in the HTML page before the JavaScript code can access them.
What does document.querySelector( ) take as its argument and what does it return?
Takes a CSS selector string as an argument and returns the first matching HTML element object.
What does document.querySelectorAll( ) take as its argument and what does it return?
Takes a CSS selector string as an argument and returns all matching elements in the form of a NodeList
What is the purpose of events and event handling?
Events occur when users interact with a web page. When an event occurs or fires, it can be used to trigger a particular function in response to that event.
What do [ ] square brackets mean in function and method syntax documentation?
square brackets mean optional
What method of element objects lets you set up a function to be called when a specific type of event occurs?
an addEventListener method
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?
object about 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 target property of the Event interface – the object onto which the event was dispatched. Check MDN for more info.
What is the difference between these two snippets of code?
element. addEventListener(‘click’, handleClick)
element. addEventListener(‘click’, handleClick( ) )
the first ‘handleClick’ is referring to a function definition. The second is referring to the return value of the ‘handleClick’ function.
What is the className property of element objects?
A string containing the value of the class on that element.
How do you update the CSS class attribute of an element using JavaScript
Use the ClassName property ElementVariable.ClassName = ‘newValue’;
What is the textContent property of element objects
A string containing the text content of the element & any child elements.
How do you update the text within an element using JavaScript?
Use the textContent property
ElementVariable.textContent = ‘newValue’
Is the event parameter of an event listener callback always useful?
The Event parameter is not always used and therefor not always necessary.
Why is storing information about a program in variables better than only storing it in the DOM?
So you can access that information more easily. If you don’t store in a variable - you’ll have to query the DOM again if you need that info again
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 as a user changes the value of 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?
Prevents the browser from automatically reloading the page
What does submitting a form without event.preventDefault( ) do?
The browser will reload the page
What property of a form element object contains all of the form’s controls.
Elements property
What property of form a 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’ll need to look through all the code to find the bug.
What is an advantage of having your console open when writing a JavaScript program?
So you can check the outputs are as expected and see any errors/bugs in your code.
Does the document.createElement( ) method insert a new element to the page?
No - you need to append that new element to an existing one to add it to the page.
How do you add an element as a child to another element?
appendChild( ) method or append( ) method
What do you pass as the arguments to the element.setAttribute( ) method?
the attribute name and value
EX: element.setAttribute(“class”, “header”)
What steps do you need to take in order to insert a new element into the page?
- Create the element - createElement( )
- Give it content - createTextNode( ) you can skip this step if you don’t want to add content.
- Add it to the DOM -
The appendChild( ) method allows you to specify which existing element you want this node added to, as a child of it.
What is the textContent property of an element object for?
textContent property can be used to get or set the text content of an element object
Name two ways to set the class attribute of a DOM element
element.className = ‘class-name’
OR
.setAttribute( ) method
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
Having a function that takes in data and returns data
makes it easy to test (in the console)
What is the event.target?
the target property of the Event interface is a reference to the object onto which the event was dispatched.
Why is it possible to listen for events on one element that actually happen its descendent elements?
Because the event starts at the most specific node and flows outwards (bubbles) to the least specific one by default.
What DOM element property tells you what type of element it is?
.tagName property
What does the element.closest( ) method take as its argument and what does it return?
Takes in a CSS selector as its argument and returns the Element which is the closest ancestor of the selected element.
How can you remove an element from the DOM?
Using the remove( ) method.
EX: element.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?
By adding the event listener to the parent element aka. event delegation
What does the element.matches( ) method take as an argument and what does it return?
It takes a string representing a CSS selector as it’s argument. and returns a boolean.
How can you retrieve the value of an element’s attribute?
element.getAttribute( ) method
What is JSON?
Text-based data format following JavaScript object syntax
What are serialization and deserialization?
Serialization is the process of turning an object in memory into a stream of bytes (taking some complex data format and converting it into a string).
Deserialization is the reverse process: turning a stream of bytes into an object in memory.
Why are serialization and deserialization useful?
Serialization is useful so you can send data over a network or store things in memory.
Deserialized data is easier to work with.
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify( ) method
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse( ) method
How do you store data in localStorage?
localStorage.setItem( ) method
How do you retrieve data from localStorage?
localStorage.getItem( ) method
What data type can localStorage save in the browser?
String
When does the ‘beforeunload’ event fire on the window object?
The beforeunload event is fired when the page is about to be unloaded.
How can you tell the difference between a method definition and a method call?
Method definition starts with a function keyword and is followed by code block.
Method call has ( ) with any arguments inside
Describe method definition syntax (structure).
propertyName: function (any parameters) { //code block }
Describe method call syntax (structure).
objectName.methodName (any arguments);
How is a method different from any other function?
A method is a property of an object
What does API stand for?
Application Programming Interface
What is “abstraction”?
Being able to work with (possibly) complex things in simple ways.
The process of removing physical, spatial, or temporal details or attributes in the study of objects or systems to focus attention on details of greater importance.
What is the purpose of an API?
is to give programmers a way to interact with a system in a simplified, consistent fashion: aka, an abstraction.
Allows users to use the interface independently of the implementation.
What is ‘this’ in JavaScript?
An implicit parameter that points to the object that we are inside of.
When is the value of this determined in a function; call time or definition time?
The value of this is determined when the function is called, not when it is defined.
How can you tell what the value of ‘this’ will be for a particular function or method definition?
If you can’t see where the function (or method) is called, then you cannot say for sure what the value of this is.
What kind of inheritance does the JavaScript programming language use?
Prototype-based (or prototypal) inheritance
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?
Those methods are defined on a “prototype” object and arrays/strings/objects simply borrow those methods when they’re needed.
If an object does not have its own property or method by a given key, where does JavaScript look for it?
In the prototype object
What does the ‘new’ operator do?
- Creates a blank, plain JavaScript object
- Links (sets the constructor of) the newly created object to another object by setting the other object as its parent prototype
- Passes the newly created object from Step 1 as the ‘this’ context
- Returns ‘this’ if the function doesn’t return an object.
What property of JavaScript functions can store shared behavior for instances created with new?
Prototype property
What does the instanceOf operator do?
The instanceOf operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
Besides adding an event listener callback function to an element or the document, what is one way to delay the execution of a JavaScript function until some point in the future?
setTimeout( ) method
How can you set up a function to be called repeatedly without using a loop?
setInterval( ) method
What is the default time delay if you omit the delay parameter from setTimeout( ) or setInterval( )?
The default time delay is 0 -execute immediately
What do setTimeout( ) and setInterval( ) return?
The returned intervalID for setInterval( ) is a numeric non-0 value which identifies the timer created by the call to setInterval( );
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout( );
What does the AJAX acronym stand for?
Asynchronous JavaScript And XML
What is AJAX?
Ajax is an asynchronous processing model that allows you to request data from a server and load it without having to refresh the entire page.
Ajax is a technique for loading data into part of a page without having to refresh the entire page.
Ajax is a programming practice of building complex, dynamic webpages using a technology known as XMLHttpRequest.
Which object is built into the browser for making HTTP requests in JavaScript?
XMLHttpRequest
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
Load event
An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
Document element objects and HMLHttpRequest objects are both chained off of the EventTarget prototype
What is Array.prototype.filter useful for?
The filter( ) method creates a new array with all elements that pass the test implemented by the provided callback function. Useful for filtering out any items that don’t meet the functions requirements.
What is Array.prototype.map useful for?
The map( ) method creates a new array populated with the results of calling a provided function on every element in the calling array.
What is Array.prototype.reduce useful for?
The reduce( ) method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
Your reducer function’s returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
What must the return value of myFunction be if the following expression is possible?
myFunction( )( );
The return value of MyFunction would have to be a function.
What does this code do? const wrap = value => ( ) => value;
Wrap is assigned a function that returns a function
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
A functions scope is determined when it is defined.
What allows JavaScript functions to “remember” values from their surroundings?
Closures allow you to store values to be used in inner functions. A closure is the inner function(s) plus it’s environment. the environment is where values are remembered