JavaScript Flashcards
What is the purpose of variables?
To give us a location to store data and information to do something with it and use it again in the future.
How do you declare a variable?
Use the var keyword and then followed by the name of the variable. example:
var totalPets =
How do you initialize (assign a value to) a variable?
Using the assignment operator ( = )
What characters are allowed in variable names?
Letters, numbers, $ and underscore.
numbers are allowed as long as it is not the first character in the value. So “cat1” works but not “1cat.”
What does it mean to say that variable names are “case sensitive”?
Being “case sensitive” means that keywords should be exact.
What is the purpose of a string?
To represent text rather than numbers.
What is the purpose of numbers?
To count, measure, and calculate.
(example: you would store it as a string because you don’t do ‘math’ with your zip code. A zip code is an identifier. Other examples include address, telephone number, and SSN)
What is the purpose of a boolean?
To define whether an expression is true or false.
Booleans’ purpose is for computers for making a choice. This gives comp only two choices: “true” or “false.”
What does the = operator mean in JS?
A symbol used to perform operations on operands (values and variables).
How do you update the value of a variable?
State var name, assignment operator and then the new value.
What is the difference between null and undefined?
null is the intentional absence of a value so then you can go back and store a value. It indicates that it does exist but it is not assigned anything.
Undefined means it is also empty but the computer will assign it as it not having any value.
Why is it a good habit to include “labels” when you log values to the a browser console?
labels describe what you are inputting. It is mainly for organization.
Give 5 examples of JS primitives.
JS primitive types are data that is not an object and has no methods or properties.
1) string
2) booleans
3) numbers (also bigint- which are for really big numbers)
4)null
5) undefined
What data type is returned by an arithmetic operation?
Number data type
What type of data type is NaN?
NaN = not a number BUT
NaN is a number data type.
What is string concatenation?
Combines more than one string together. It’s like a secondary functionality for the + operator other than for math.
What purpose(s) does the + plus operator serve in JavaScript?
It can concatenate string and serves as an addition command, adding numbers together.
What data type is returned by comparing two values (, ===, etc)?
Boolean values.
What does the += “plus-equals” operator do?
Takes right operand value and adds it to current value (left operand) and then becomes the new value of the left operand.
What are objects used for?
Group together a set of properties to store data.
What is the reason to group data together to make objects?
Objects are a collection of variables to put them in a category indicating that they are similar.
What are object properties?
Individual pieces of data assigned as a variable that is associated with an object.
Describe Object Literal Notation.
It starts with a variable and it is defined by an array of key:value pairs separated by colons and then a comma after every key:value pairs except for the last pair of the array.
example:
var student = {
firstName: ‘Sharon’,
lastName: ‘Tieu’
};
How do you remove a property from an object?
use the Delete operator or use dot notation or bracket notation.
What are the two ways to get or update the value of a property?
Dot notation or Bracket notation.
What are arrays used for?
Arrays are typically lists of data especially when we do not know how much data will be in this list.
They are special type of objects that hold a set of related key/value pairs but the key for each value is its index.
Describe array literal notation.
- state variable
- assignment equal operator
-followed by [ ] - inside the [ ], you list the values
How are arrays different from “plain” objects?
Objects are individually named data stored inside of them whilst an Array is data with an specific order
Objects do not have an order whereas Arrays do have an order.
How do you calculate the last index of an array?
length property - 1
example:
student.length - 1;
What number represents the first index of an array?
0
What is the length property of an array?
The total number of values that exists in the array.
What is the importance of Data Modeling?
Data models are an organization of data.
What is a function in Javascript?
In Javascript, Functions are are expressions that establishes a relationship between an input and output.
To interact with a function in JS, you can “define” a function or “call” a function.
Example:
function sayHello() {
var greeting = ‘Hello, World!’;
console.log(greeting);
}
Describe the parts of a function definition.
function sayHello( ) {
var greeting = ‘Hello, World!’;
console.log(greeting);
}
- The function keyword - begins the creation of a new function
a. example: function - An optional name
a. example: (our function’s name is sayHello.) - A comma-separated list of zero or more parameters, surround by ( ) parentheses
a. example: (Our sayHello function does not have any parameters.) - The function’s code block, as indicated by an { opening curly brace
- An optional return statement
a. example: (Our sayHello function does not have a return statement.) - The end of the function’s code block
a. example: as indicated by a } closing curly brace
Explain the difference between “Defining” a function and “Calling” a function. How does calling a function work?
(Defining a function IS DIFFERENT from calling a function- defining a function does NOT cause the code’s code block to run.)
Once defined, a function becomes another kind of object, however, now it is special in that it can now be CALLED. A function has to be called in order for the code’s code block to run.
Example:
sayHello( ); // will log “Hello, World!” into the console.
var greeting = ‘Hello, World!’;
console.log(greeting);
//can now be executed again and again by name without having to copy-paste the code inside over and over again.
Describe the parts in calling a function. (Describe the function call syntax)
example(arg1, arg2, arg3);
- the function’s name.
(in this case, our function’s name is called example.) - A comma-separated list of zero or more arguments surrounded by ( ) parenthesis.
(Our sayHello function does not have any arguments.)
The only way to call a function is parenthesis.
When comparing them side-by-side, what are the differences between a function call and a function definition.
Function definition:
- include function keyword and a code block
Function call:
- will have parenthesis **
What is the difference between a parameter and an argument?
Parameter - variables that are defined when the function is declared. These are initialized to the values of the arguments supplied. They are local variables to the function that can store values.
Argument - the real values that are actually stored there when the function is called.
Why are function parameters useful?
Function parameters are useful, because you can pass in certain data to be able to run it again which saves you time from writing several different codes to serve the same function.
What two effects does a return statement have on the behavior of a function?
- The return statement will be replaced by whatever the function called.
- A return statement also will stop the function entirely.
What is a method?
A method is a function which is a property of an object. There are two kinds of methods:
1) Instance Methods: built-in tasks performed by an object instance
2) Static Methods: tasks that are called directly on an object constructor.
Why do we use log things to the console?
To see if our code is working and running. It’s meant for checking values while we are debugging.
How is a method different from other functions?
Methods are associated with an object, while a function is not.
a method is a form of a function- but they’re just stored in an object.
How do you remove the last element from an array?
pop( ) method removes (pops) the last element of an array.
How do you generate a random number?
Math.random( )
How do you round a number down to the nearest integer?
Math.floor( )
How do you append an element to an array? (append = add to the end)
push( ) method
How do you break a string up into an array?
split( ) method
Is the return value of a function or method useful in every situation?
No.
example: pop( )
The pop( ) method has a return value that is the removed element of an array. It is meant to get rid of something but on the console.log( ) it will show you what you have removed.
Roughly how many array methods are there according to the WDN Web docs?
there’s a lot :3
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
6 examples of comparison operators.
greater than >
less than <
strictly equal to === (makes sure values are the same if data type and value are equal)
!== strict not equal to
!= is not equal to
What data type do comparison expressions evaluate to?
Booleans (true or false)
Describe the syntax of an if statement.
define function with a parameter.
if statement, opening ( with condition ) { opening curly brace, then a return statement ; then semicolon, then } closing curly brace for the if statement.
function introduceWarnerBros(name) {
if (name === ‘yakko’) {
return ‘we are the warner brothers’;
} ;
What are the three logical operators?
and , or, and not
&& and: both needs to be true to be true
|| or : one condition to be met.
! not:
How can two different expressions in the same condition be compared?
With Logical Operators
What are truthy values? Give an example.
A value that is considered true when encountered in a Boolean context.
Example: the string of “space” so ‘ ‘ and an empty object, even empty arrays (because objects and arrays take up space and memory!)
What are falsy values?
A value that is considered false when encountered in a Boolean context.
Example: NaN
What is the purpose of an if statement?
It allows the computer to make a decisions based on the criterias that we set.
What is the purpose of a loop?
To run a set of code(s) over and over again.
What is the purpose of a condition expression in a loop?
They are the “brakes” or checkpoints for your loop
What does “iteration” mean in the context of loops?
“iteration” is the number of times your code block loop runs on a repetitive basis.
When does the condition expression of a While loop get evaluated?
The condition expression of a While loop gets evaluated before each iteration. It is a way to check to see if the code block can even run.
When does the initialization expression of a For loop get evaluated?
The initialization expression gets evaluated ONCE BEFORE the loop begins.
When does the condition expression of a loop take place?
Before each iteration takes place.
When does the final expression of a for loop get evaluated?
After each iteration takes place.
Besides a return statement, which exits its function block, which keyword exits a loop before its condition expression evaluates to false?
Break
What does the ++ increment operator do? ( the difference between a++ and ++a ).
- Substitutes the operator
- and increments the variable by one
How do you iterate through the keys of an object.
For - in loop
Why do we log things to the console?
To make sure everything is loading properly. Helps with debugging and to make sure the code is running.
What is a “model”?
A model is a representation or recreation of something.
Which “document” is being referred to in the phrase Document Object Model?
The HTML document.
What is the word “object” referring to in the phrase Document Object Model?
The word “object” refers to the data type object in javascript.
What is a DOM Tree?
Document Object Model is a model of the HTML document that is represented as javascript objects.
So The DOM Tree is the representative chunk of a page as javascript objects.
Give two examples of document methods that retrieve a single element from the DOM.
- document.querySelector( )
** only use this one^^ - document.getElementById( )
Give one example of a document method that retrieves multiple elements from the DOM at once.
- document.querySelectorAll( )
** only use this one^^ - getElementByClassName( )
- getElementsByTagName( )
Why might you want to assign the return value of a DOM query to a variable?
You can save it in the DOM once so then you don’t have to search for it again.
What console method allows you to inspect the properties of a DOM element object?
The director method: .dir( )
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
The HTML document loads from top to bottom and so when the javascript script elements needs to be at the bottom of the body so then the entire body would have already been loaded.
What does document.querySelector() take as its argument and what does it return?
It takes a string as an argument and returns the first instance of that element matching that pattern in the document.
It can be a class, type, or so on- querySelector is like a CSS selector.
returns: An Element object representing the first element in the document that matches the specified set of CSS selectors, or null is returned if there are no matches.
What does document.querySelectorAll() take as its argument and what does it return?
.querySelectorAll( ) selects all the elements that you are put as a string argument. The argument is a string that contains a css selector. It will return a static Node List which is a list of DOM elements. This is an example of an array-like object.
Why do we log things to the console?
To make sure everything is loading properly. Helps with debugging and to make sure the code is running.
What is the purpose of events and event handling?
Event handlers are to list of actions that are set up and happens when an action occurs.
This leads to user interactivity to see what users have done.
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 that is passed into another function as an argument. It 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?
The event object or the object with all of the data of that event that just occurred.
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 stores the DOM element of where the action originated from.
The importance of event.target is that it can get the element that fired the event, access the properties of the element, and modify some properties of the element, the CSS, and the attributes, etc.
What is the difference between these two snippets of code?
1: element.addEventListener(‘click’, handleClick);
2: element.addEventListener(‘click’, handleClick( ) );
- variable named handleClick that’s being passed as an argument. It is being called when you click. Sets up an event listener, and says when the element is clicked then the handleClick function is invoked.
2: handleClick( ) is a function being invoked from the function (with undefined parameters). The function is called right away instead of letting the browser call it when it happens. This function has no return value, it will be “undefined.” (This will NEVER be the thing that you would want to do btw).
This is passing the return of this function and will return undefined because it doesn’t return anything.
What is the className property of element objects?
The className property of the Element object sets the value of the class attribute of the specified element.
Allows us to get the value inside of it or set a new element.
How do you update the CSS class attribute of an element using JavaScript?
select the element first, get class name property and assign a new variable to it.
class.className =
What is the textContent property of element objects?
You can get what’s currently there or assign a new variable.
How do you update the text within an element using JavaScript?
Get your element (whether that’s querySelector( ) ) and then use the .textContent method and assign it to a string.
element.textContent = ‘ string of whatever you want to update’
Is the event parameter of an event listener callback always useful?
No- you don’t always have to use the event listener callback- you use it when you need it.
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
For the dom-manipulation exercise, it would be more complicated.
Why is storing information about a program in variables better than only storing it in the DOM?
Variables are easy to change in Javascript but it’s harder to change in HTML.
Does the document.createElement( ) method insert a new element into the page?
No, it creates a node in the dom
How do you add an element as a child to another element?
.appendChild( ) method
What do you pass as the arguments to the element.setAttribute() method?
We pass two strings: the name of the attribute and the value being applied to that attribute.
What steps do you need to take in order to insert a new element into the page?
create the element with document.createElement( ) and assign it a variable.
Create a class name for it with .setAttribute( ) and then append it as a child to its parent.
What is the textContent property of an element object for?
attaches text
Name two ways to set the class attribute of a DOM element.
- .setAttribute ( ) method
- there is a property named className that you can use to set the name of the attribute.
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
- makes it reusable
- makes it efficient and saves time so we don’t have to write the same function over and over again.
What is the event.target?
The element that triggered an event. In other words, where the event originated from.
What is the affect of setting an element to display: none?
It is removed from the document flow entirely. It’s technically still there and it still exists, but to the user, they cannot see it.
What does the element.matches() method take as an argument and what does it return?
It takes a css selector as a string and returns a Boolean value if it matches the corresponding element.
How can you retrieve the value of an element’s attribute?
The getAttribute() method of the Element interface returns the value of a specified attribute on the element.
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?
You would have to add individual eventListeners for each individual 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?
We would have to write a condition for each possible view.
What is JSON?
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 (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
Specifically, JSON is a string whose format resembles JavaScript object literal format. You can include the same basic data types inside JSON as you can in a standard JavaScript object - strings, numbers, arrays, booleans, and other object literals.
What are serialization and deserialization?
Serialization: the process of turning an object in memory into a stream of bytes so you can do stuff like store it on a disk or send it over the network.
(converting an Object into a stream of bytes so it can be transferred over a network or a consistent storage.)
Deserialization: the reverse process of serialization: turning a stream of bytes into an object in memory.
Why are serialization and deserialization useful?
serialization: to easily transmit data to somewhere else.
deserialization: trying to get a piece of data out of a larger string.
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify( )
argument: an array or object
return: a JSON string
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse( )
argument: a JSON string
return: an array or object
How do you store data in localStorage?
using the setItem( ) method of the localstorage object.
the arguments of setItem( ) are:
1. keyName: a string containing the name of the key that you want to create/update
2. keyValue: a string containing the value you want to give the key you are creating/updating
How do you retrieve data from localStorage?
using the getItem( ) method.
the argument of getItem( ) is:
1. keyName: a string containing the name of the key you want to retrieve the value of.
What data type can localStorage save in the browser?
localStorage stores Strings.
When does the ‘beforeunload’ event fire on the window object?
Just before the document loads such as refreshing your document, closing your tab, or closing your browser.
What is the purpose for localStorage.
To store values to be used for later for the user.
What is the event.target?
Helps you find the element of where the target originated from.
Why is it possible to listen for events on one element that actually happen its descendent elements?
Event bubbling
What DOM element property tells you what type of element it is?
The DOM element property that tells you the type of element is called tagName or nodeName.
tagName represents element names while
nodeName refers to white space nodes or text nodes
What does the element.closest() method take as its argument and what does it return?
element.closest( ) takes the closest parent selector and can go up the ancestral chain. It’s like a reversed querySelector( ), because element.closest( ) returns the parent selector.
It will return null if it cannot detect what you are selecting.
How can you remove an element from the DOM?
.remove() element
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?
add the .addEventListener( ) method to the parent element.
What is a method?
A function that is stored into a property of an object.
There are two different kinds of methods: Static Method and Instance Method.
How can you tell the difference between a method definition and a method call?
method Definition defines function definition and assigns it to a property.
A method Call is an object.methodname.( )
Describe method definition syntax (structure).
property: anonymousFunction (parameters) {
variable then an assignment operator (=) followed by the result of that method;
return variable;
};
example:
add: function (x , y) {
var sum = x + y;
return sum;
};
Describe method call syntax (structure).
use dot notation of the object to access it and then parenthesis to call the function:
nameOfObject.nameOfMethod ( arguments );
How is a method different from any other function?
It is stored inside an object.
** What is the defining characteristic of Object-Oriented Programming?
OOP is to create objects that can carry data and behavior as methods within a shared space.
What are the four “principles” of Object-Oriented Programming?
- Abstraction
- Encapsulation
- Inheritance
- Inheritance
What is “abstraction”?
A simpler way to access complex behavior. It is a means to simplify w/o having to fully understand the complexity of it. You can do something without understanding all of the complex stuff needed to perform a certain behavior.
What does API stand for?
Application Programming Interface.
What is the purpose of an API?
A set of tools that allow you to access complex functionalities.
Ex: the DOM.
What is this in JavaScript?
In JS, the keyword “this” refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: in an object method, this refers to the object.
What does it mean to say that this is an “implicit parameter”?
“Implicit parameter” means it is a parameter being invoked in a function that is not being directly stated or listed in the function but it is being used.
parameter = a var that we create in a function definition that serves as a placeholder until it is called
implicit = “implied” which means it is present even though it is not directly state.
When is the value of this determined in a function; call time or definition time?
Call time.
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);
}
};
the value of this is: nothing. this is no value.
because! you are not calling it during call time.
What does this refer to in the following code snippet?
character.greet( );
result is: It’s-a-me, mario!
this: character (becaue character is to the left of the “dot” in character.greet( );
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?
this:
there is nothing left of the dog.
character.greet();
Given the above character object, what is the result of the following code snippet? Why?
It’s-a-me, Mario!
var hello = character.greet;
hello();
How can you tell what the value of this will be for a particular function or method definition?
Look at the left of the dot (which is the calling object), it will let you know what THIS is referring to.
var hello = character.greet;
hello();
How can you tell what the value of this is for a particular function or method call?
Look at the object to the left of the dot. So in this case, it is character.
What kind of inheritance does the JavaScript programming language use?
Prototypal inheritance. This means an object “inherits” properties from another object via the prototype linkage.
What is a prototype in JavaScript?
A prototype is an object or behavior that has access / inheritance of another object via prototype linkage.
How is it possible to call methods on strings, arrays, and numbers even though those methods don’t actually exist on strings, arrays, and numbers?
Through Prototypal Inheritance.
If an object does not have its own property or method by a given key, where does JavaScript look for it?
It will look for it in the prototype.
What does the new operator do?
The new operator lets you create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
What property of JavaScript functions can store shared behavior for instances created with new?
The prototype property. This will hold an object and this object will store shared behavior that is created with new.
What does the instanceof operator do?
The instanceof operator tests the presence of constructor.prototype in object’s prototype chain. The value of instanceof test can change depending on the changes to the prototype property of constructors. It can also be changed by changing an object’s prototype using Object.setPrototypeOf( ) ;
left side is the variable or whatever you want to check and the right will be a function definition.
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( ); function
How can you set up a function to be called repeatedly without using a loop?
setInterval( ); function
What is the default time delay if you omit the delay parameter from setTimeout( ) or setInterval( )?
0 milliseconds
What do setTimeout( ) and setInterval( ) return?
The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval() ; this value can be passed to clearInterval() to cancel the interval.
setInterval() returns a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to clearInterval() to cancel the interval.
(http-messages) What is a client?
Clients are server requesters. So someone who wants a certain service.
What is a server?
Servers are a piece of computer hardware or software (computer programs) that provides functionality for other programs or devices called “clients.” Servers share data and resources amongst clients or to perform certain computations.
Which HTTP method does a browser issue to a web server when you visit a URL?
The browser issues a GET or POST request method to a web server when we visit a URL.
What are the three things on the start-line of an HTTP *request message?
The 3 things on the start-line HTTP request message are:
1. description of the request to be implemented
2. status of whether it is successful or a failure
3. the start-line will always be a single line.
What are the three things on the start-line of an HTTP *response message?
The 3 things on the start-line HTTP Response message are:
1. The protocol version (usually HTTP/1.1).
2. The status code: to indicate success or failure of the request. (Common status codes are 200, 404, or 302).
3. A status Text: a brief, purely informational, textual description of the status code to help humans understand the HTTP message.
A typical status line looks like:
HTTP/1.1 404 NOT FOUND
What are HTTP headers?
HTTP headers allow the client and server to pass information with an HTTP request or response.
HTTP headers consists of its case-insensitive name followed by a colon ( : ), then by its value.
In other words, this is meta-data that provides additional information. This is the equivalent of the element in an HTML document :3
In other words, a HTTP Header is a field of an HTTP response or requests that passes additional context and metadata about the response or requests.
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN
Is a body required for a valid HTTP request or response message?
No. A body is optional for a valid HTTP request or response message.
example: 201
What is AJAX?
A programming practice of building complex, dynamic webpages using XMLHttpRequest. This is what makes a webpage dynamic
What does the AJAX acronym stand for?
Asynchronous JavaScript and XML.
Which object is built into the browser for making HTTP requests in JavaScript?
new XMLHttpRequest( );
What event is fired by XMLHttpRequest objects when they are finished loading the data from the server?
‘load’
Bonus Question: An XMLHttpRequest object has an addEventListener( ) method just like DOM elements. How is it possible that they both share this functionality?
Because of prototypal inheritance.
Explain the syntax of event.target.
The target property can only be obtained if the event of an element is being listened to.
element.addEventListener(“input”, function(event) {
//event.target is now accessible
console.log(event.target)
})
How do you round a number down to the nearest integer?
Math.floor( )
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?
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a “Submit” button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
In other words, it prevents the default behavior of the method.
it should always be the first in a form function.
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?
it will be difficult to debug and to pinpoint where your mistake is and to fix it. Limit the stuff you need to fix by continuously checking on your progress.
What is an advantage of having your console open when writing a JavaScript program?
You can debug right away when something doesn’t work
What does submitting a form without event.preventDefault() do?
it will refresh the page and submit the data to the URL
what is an api?
Application Programming Interface.
API is the messenger that takes requests and tells the server system what the client wants to do and returns a response back.