JavaScript Flashcards
What is the purpose of variables?
to store values to be called upon later
how do you declare a variable
using a keyterm (var, let, const)
how do you initialize a variable?
using an equal sign
what characters are allowed in variable names?
$, _, letters (cap and no cap), numbers (cannot start with a number), non keyword (e.g. var), - , .
What does it mean by variables are case-sensitive?
var Cat and var cat are two separate variables
what is the purpose of a string?
to store letters/words/phrases values
what is the purpose of a number?
to store number values
what is the purpose of a boolean
to store true and false values (values that can only be 1 of the 2)
what does the = operator mean in JS?
a value is being assigned to something else
how do you update the value of a variable
assign it a new value
what is the difference between null and undefined?
null is user-defined emptiness, it is intentional and has to be assigned by the programmer (intentional emptiness)
undefined can be assigned by JS to create absence (usually not assigned by programmer)
Why is it a good habit to include labels when you log values to the browser console?
so you know which value you are logging and potentially where to find it
what are objects used for?
used to group similar properties together for ease of calling the values
what are object properties?
Object properties are variables within an object, usually are related or similar to the other properties within an object.
what are two ways to get or update the value of a property?
dot notation and bracket notation
object.property
object[‘property’]
what data type is returned from an arithmetic operation?
numbers
What is string concatenation?
addition for string values
what purpose does the + operator have in JS?
adds two values together
What data type is returned from using comparator operators? (greater than, less than, ===)
boolean (true/false)
what does the += operator do?
takes the existing value of a variable, adds another value to it, then assigns the new value back to it.
what are objects used for?
used for grouping up similar properties with values together for ease of access later
What are arrays used for ?
creating a numbered list of values, number of items within an array can be modified
describe array literal notation
[ value, value, value, value]
how are arrays different from “plain” objects?
arrays have a numbered index, order, and use [ ].
What number represents the first index of an array?
0
what is the length property of an array?
counts the number of indexes inside an array.
how do you calculate the last index of an array?
array[array.length - 1]
describe object literal notation
{ prop: value, prop: value, prop: value }
how do you remove a property from an object
using delete operator, followed by the object.property
delete object.property
what is a function?
reusable block of code that is able to receive different inputs and return different outputs based on those inputs
what is an expression?
a block of code or work that the computer needs to perform before it can assign it as a value.
what are the parts of a function definition?
keyword (function), optional function name, optional paramater list, { }, optional return
what are the parts of a function call
function name( ), argument function(argument)
What are the differences between a function call and function definition?
function call has argument instead of parameter, does not have the function keyword, no function code block.
What is the difference between a parameter and argument?
parameter is a placeholder for when defining a function, argument is a value that is actually passed through the function when calling the function.
Why are function parameters useful?
They are a placeholder for values to be passed through a function, let the user of the function know what arguments are allowed in the function
What two effects does return have on the function?
ends the function and pushes results of the work done inside the function outside so that it can be accessed
why do we log things in the console?
to check for errors in the code/ debugging
what is a method?
a method is a function that exists as a key in an object
How is a method different from any other function?
theyre effectively the same, a method just exists inside an object
how do you remove the last element of an array?
pop method of the array object
array.pop()
How do you round a number down to the nearest integer?
Math.floor() or Math.trunc()
How do you generate a random number?
Math.rand();
How do you delete an element from an array?
string.splice(index position to start, number of elements to remove, any elements to add starting from the splice start position)
How do you append an element to an array?
array.push(element)
how do you break a string up into an array
string. split(what is being split)
e. g. ‘ ‘ would split it at every space, ‘’ would split at every character
how do you capitalize all the letters in a string?
string.toUpperCase();
Do string methods change the original string? how would you check
no, console.log
how many string methods are there according to MDN web docs?
~30
Is the return value of a function or method useful in every situation?
some functions/methods do not need a return
how many array methods are there according to mdn docs?
~40
what three letter acronym should you always include in your google search about a JS method or CSS property?
mdn
6 examples of comparison operators
greater than, less than, greater than and equal to, less than and equal to, absolutely equal to, equal to (dont use), absolutely not equal to, equal to
what data type do comparison expressions evaluate to ?
boolean
what is the purpose of an if statement?
create conditionals
is else required in order to use an if statement?
no
Describe the syntax (structure) of an if statement
if keyword, followed by a condition, followed by the if-code block. condition is made up of two operands with an operator sandwiched between
What are the three logical operators?
and, or, not - &&, ||, !
how do you compare two different expressions in the same condition?
using $$ or || (and / or)
What is the purposed of a loop?
To run a designated block of code a number of times
what is the purpose of a condition expression in a loop?
It allows for the computer to know when to end the loop (once the condition fails)
What does iteration mean in the context of a loop?
each run through the loop is a single iteration
when does the condition of a while expression for a while loop get evaluated?
Before running the code inside the while loop code block.
When does the initialization expression of a for loop get evaluated?
when the loop is first read by the computer, it will initialize the initialization expression. Only done once, before the first condition expression
What is a falsey or truthy value?
values that JS coerces into a boolean value when placed in the context of a conditonal statement.
What are falsey values?
false, undefined, ‘empty string’, “empty string”, 0, -0, NaN, 0n, null, undefined
What are nodelists
an object created from using querySelectorAll, not a dom element, is a list of dom elements to prevent change to them. it is an array-like object.
what does the $ sign mean typically in dom?
stylistic choice; if used, all dom elements should be named using a $ in order to separate it from other variables. (should be used for the dom element rather than the content - only attached to values assigned to from query selector and queryselectorall)
what is event handling?
code that is executed to respond when an event has happened, to “handle” that event ( most events will be user controlled, but some can be controlled by time etc)
something to do in response to an event occurring
difference between event listener and handler?
event listeners designed to wait for an event to occur, and then invokes a list of functionalities that then occurs when the event occurs, event listeners call the event handler when the event occurs
when does the condition expression of a for loop get evaluated?
after the variable is declared, but before the code inside the for loop declaration block is run.
when does the final expression of a for loop get evaluated?
after the for loop code block gets executed, before the condition expression kicks in again
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?
increases the variable value by 1
how do you iterate through the keys of an object
for in loops
why do we log things to the console?
to make sure our expectations meet our results/ check for bugs in the code
What is a ‘model’
a representation of something, a smaller version that is equally if not as detailed as the original
which document is referred to in the phrase Document Object Model
html
What is the word object referring to in the phrase Document Object Model
the document object refers to the virtual object formed by js to interact with the html/css code
What is a DOM Tree
a model of dom in a tree structure, allows you to find the relationships between each node/element and therefore how to access each one
give two examples of document methods that retrieves a single element from the DOM
document.querySelector(), getElementByID()
document method that retrieves multiple elements form the DOM at once
document.querySelectorAll();
Why might you want to assign the return value of a DOM query to a variable?
to make it easier to access for later uses instead of having to recall it again everytime
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 element instead of the top?
The DOM is created at the instance the script is run, if the script is before the HTML code, nothing will be read. The DOM is loaded in after all the css and html is loaded into the page
What does document.querySelector take as its argument and what does it return
it takes a css. selector and returns the first child element of that selector
What does document.querySelectorAll() take as its argument and what does it return?
it takes a css selector as its argument and returns all elements of that type as a nodelist
what is the purpose of events and event handling?
to allow for user interactivity with the webpage
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 functoin?
a function that is passed through another function as an argument, and then invoked inside the outer function to complete action or routine
what object is passed into an event listener callback when the event fires?
an event object
What is the event.target?
a reference to the object that was targeted when the event was dispatched
what is the difference between
element.addEventListener(‘click’, handleClick)
and
element.addEventListener(‘click’,handleClick())?
the second one calls the handleClick function, causing it to execute it immediately - second one waits until the ‘click’ event occurs before calling the function.
what is the className property of element objects
it is all the values of the class attribute in an html element (the classes refer to css classes). can be set with the className property
How do you update the css class attribute of an element using Javascript?
using className, classList, or dom-creation setAttribute()
What is the textContent property of element objects?
it is the user-readable text content in an html element
how do you update the text within an element using JavaScript?
element.textContent = ‘updated-text’;
is the event parameter of an event listener callback always useful? (function inside an eventlistener)
no, sometimes the function can be run without any input from the event itself (aside from activating the function call)
would this assignment be simpler or more complicated if we didnt use a variable to keep track of the number of clicks?
its easier because we’d be able to debug it in the case that it breaks (e.g. buttons classes changes not being applied with click count, color not changing when button classes change)
why is storing information about a program in variables better than storing it in the dom?
They are more accessible through the console.log
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 form?
submite event
what does the event.preventDefault()
prevents the event’s default behavior from occurring
what does submitting a form without event.preventDefault() do?
does not prevent the default behavior of the form, in the case that theres no action, ends up refreshing the page
what property of a form element object contains all of the form’s controls?
the elements property
what property of a form control object gets and sets its value?
setAttribute()
What is one trick of writing a lot of code without checking to see if it works so far?
if something goes wrong or theres a bug in the code, it’s hard to pinpoint the root of the problem
what is one advantage of having your console open when writing a javascript program?
you can see in real time if your code is creating bugs and therefore solve them or correct them before the code gets too convoluted
does the document.createElement() method insert a new element into the page
no, it only creates the element in the dom, it still needs to be appended into the actual document
how do you add an element as a child to another element?
you append it with the appendChild() or append methods
WHat do you pass as the arguments to the element.setAttribute method?
the value you want to set it to (as a string) and the value (as a domstring value)
what steps do you need to take in order to insert a new element into the page
first you need to create the element, then you need to append it to an element that exists in the document page already
What is the textContent property of an object for ?
allows you to get or set the user-readable text in an element object
what are two ways to set the class attribute of a DOM element?
setAttribute, classList.add/remove, nameClass
What are two advantages of defining a function to do create something (like the work of creating a dom tree)
makes it so that it can be reusable, and helps define the purpose of that segment of code
give two examples of media features that you can query in an @media rule
min-width and max-width
Which HTML meta tag is used in mobile responsive web pages
viewport meta tag
what is the event.target?
it is a dom element object that points to the element that is being targeted by an action
why is it possible to listen for events on one element that actually happens to its descendent elements?
due to dom event delegation (bubbling)
What DOM element property tells you what type of element it is?
event.target.tagName - returns element type as a string in all caps
What does the element.closest method() take as its argument and what does it return?
it takes a css selector as its argument, returns everything from itself to the nearest ancestor element towards the root with that specified css selector
How can you remove an element from the DOM
using the remove method of that element (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?
attach the event listener to the parent element of the elements you want to control, that way any amount of elements added or removed can be affected through the parent element
What is the effect of setting an element to display:none?
it hides the element from the viewport
what does the element.matches() method take as an argument and what does it return?
it takes a css selector and returns a boolean
How can you retrieve the value of an elements attribute?
using the getAttribute() method of the element object
At what steps of the solution would it be helpful to log things to the console
inside/outside loops, to check event listeners are working properly, checking the conditions of loops, any variables being updated
If you were to add another tab and view to your HTML, but you didnt use event delegation, how would your JS code be written instead?
you’d have to create a new event Listener
What is JSON
JavaScript Object Notation; it is an interchange data type used to transmit and store data
what are serialization and deserialization?
serialization converts data into a contiguous series of bytes so it can be stored in memory or sent elsewhere whereas deserialization is turning that series of bytes into readabe data
Why are serialization and deserialization useful?
Serialization lets you send data out, deserialization makes reading that data easier so that you dont have to parse the serialized data every time you want to access the inner objects
How do you serialize data into a JSON string in JavaScript?
using the stringify method (JSON.strigify())
How do you deserialize a JSON string into a data structure using JavaScript?
using the parse method of the JSON object (JSON.parse())
How to you store data in localStorage
setItem method (localStorage.setItem()
How to you retrieve data from localStorage?
using the getItem method (localStorage.getItem())
What data type can localStorage save in the browser?
JSON string
When does the ‘beforeunload’ event fire on the window object?
before the page unloads
What is a method?
A method is a function that is a property of an object
How can you tell the difference between a method definition and a method call?
a method definition will have the function keyword, followed by the method name and any parameters. the method call will just have just the method name and any arguments
Describe method definition syntax
name of the method property, followed my a colon to show that you’re assigning it a value. follow it with the function keyword, an optional name (if you want to call it on itself), any parameters, the code block, then a comma if there are any additonal properties after it
Describe method call syntax (structure)
call the object followed by the property name for that function
How is a method different from any other function?
you have to call as a property of its object first, it’s not “freestanding” and can be called by itself like a function can
What is the defining characteristic of Object Oriented Programming?
You can store both properties and methods together (data and behavior)
What are the four prinicples of OOP
abstraction, encapsulation, inheritance, polymorphism
What is abstraction?
being able to work with complex things in simple ways e.g. light switch or DOM API
What does API stand for?
Application Programming Interface
What is the purpose of an API
to let two computers or programs interact with each other
What is “this” in JavaScript
it points to the nearest Object “this” is inside of, the window if its not inside another object
What does it mean to say that this is an implicit parameter?
This inherently does have a value, it is only given when a function is called
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 window
given the above character object, what is the result of the following code snippet? why?
var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } };
character.greet();
“it’s a me Mario” b/c the this was defined when the method was called
given var character = { firstName: 'Mario', greet: function () { var message = 'It\'s-a-me, ' + this.firstName + '!'; console.log(message); } }; What is the result of the following code snippet? why? var hello = character.greet; hello();
‘It’s a me, undefined’ b/c hello is a property of the window object. This now points to the window object, so when it looks for window.firstName, it is unable to find it and returns undefined.
How can you tell what the value of this will be for a particular function or method definition
it’ll be nothing because it has no value, it is an implicit parameter, it is only defined at function call, not function/method definition
How can you tell what the value of this is for a particular function or method call?
it’ll be pointing to the object on the left of the . for a method.
What kind of inheritance does the JavaScript programming language use?
prototype
What is a prototype in JavaScript?
it is an object or object like structure that descendants of that prototype will inherit properties or methods from
How is it possible to call methods on strings, arrays, and numbers even though those methods dont actually exist on strings, arrays, and numbers?
They all have a prototype object that they inherit specific property and methods from
IF an object does not have its own property or method by a given key, where does JS look for it?
it looks for it in its prototype
What does the new operator do?
- Creates an empty plain JavaScript object
- adds a property to the new Object that links to the constructor function’s prototype object
- binds newly created object instance as the this context (all references to this in the constructor function now point to the object created in the new op step)
- returns this if the function doesnt return an object
What property of Javascript functions can store shared behavior for instances created with new?
prototype
What does the instanceof operator do?
Checks if the target object has any lineage that includes the prototype property of a specified constructor
What is a callback function
it is a function that is used as an argument in another function
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() and setInterval()
How can you set up a function to be called repeatedly without using a loop?
using the setInterval() method
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
no time delay
What do setTimeout() and setInterval() return?
a timeout ID to identify the timer created by the method
what is a client?
Does not usually share resources, but does request content or services from a server
What is a server
runs one or more server programs that share resources with clients when requested
Which HTTP method does a browser issue to a web server when you visit a URL?
GET
What three things are on the start-line of an HTTP request message?
HTTP method (get, post, put, delete), request target (URL, absolute path), HTTP version (usually 1.1, maybe 2)
What three things are on the start line of an HTTP response message?
version, status code, status message
What are HTTP headers?
provide additonal information about the body of the response, about the data; metadata
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
What is AJAX?
programming practice of building complex dynamic webpages
What does the AJAX acronym stand for?
Asynchronous Javascript and XML
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?
share the same prototype ancestor (eventtarget)
What is a code block? What are some examples of a code block?
A code block is a snippet of code that is grouped together within curly braces, function code block, condition code block
What does block scope mean?
Block scope means within the block of code where a variable can be defined
What is the scope of a variable declared with const or let?
block scoped for both (local)
What is the difference between let and const?
Const is immutable ( like a string ) and creates a read-only reference to a value, let can be mutated
Why is it possible to .push a new value into a const variable that points to an Array?
the variable created by const becomes read-only, but the value the property points to is still mutable (cant reassign a variable created by const, but can change things inside)
How should you decide on which type of declaration to use?
Const should be used if the variable will never be reassigned, let allows you to reassign that variable as much as needed
What is the syntax for writing a template literal?
instead of single quotes or double quotes around the content you want to encapsulate, you use back-ticks ( ` ), any javascript expression is written as ${expression/variable}
What is “string interpolation”?
String interpolation is where parts of the string are replaced with variable values or expressions
What is destructuring, conceptually?
taking apart the property/values of an object and assigning them to variables
what is the syntax for destructuring for objects?
const/let {variable_name: property_name/value you want to assign} = object (object you are obtaining the property’s value from)
What is the syntax for destructuring arrays?
const/let [var 1, var2, … varX] = array_name
var1 = element at first index
var2 = element at second index
varX = all other elements leftover (due to the spread operator […])
How can you tell the difference between destructuring and creating object/array literals?
depends on which side the object/array literal notation is on; if the curly braces/ array is on the left, it is destructuring. if it’s on the right side, it’s constructing.
what is the syntax for defining an arrow function?
let/const/var function_name = paramater or (x, y, …z) or ( ) => expression or { if code is longer than one line}
When an arrow function’s body is left without curly braces, what changes in its functionality?
the expression denoted by the arrow function is implicitly returned
How is the value of this determined within an arrow function?
it is determined when the arrow function is defined
what is a CLI ?
command line interface
what is gui
graphical user interface
One use case for each of the following:
man , cat, ls, pwd, echo, touch, mkdir, mv, rm, cp
man - pulls up manual, cat - concatenates the contents of two files together, ls - lists all files and directories within a level of a directory, pwd - prints current file location, touch - updates files, creates them if they are not present, mkdir - makes directory, mv - moves file location, rm - removes file or directory PERMANENTLY, cp - copies file or directory
What are the three virtues of a great programmer?
Laziness, impatience, and hubris
What is node.js
Node.js is a program that allows users to use JavaScript to be run outside a web browser
What can node.js be used for?
used to build back-end for web-apps, command-line programs, things you want to automate
What is REPL?
REPL (read-eval-print loop) is an interactive shell that takes in user inputs, executes them, and then returns the result back to the user
When was node.js created?
May 27, 2009
What back-end languages have you heard of?
python, PHP, JavaScript, Java, C#
what is the process object in a Node.js program?
It refers to the Node.js program itself running
How do you access the process object in a Node.js program?
console.log(process);
What is the data type of process.argv in Node.js
array of strings
what is a JavaScript module?
an individual JavaScript file is treated as its own separate module
What values are passed into a Node.js module’s local scope?
exports, require, module, __dirname, __filename
Give two examples of truly global variables in a Node.js program.
process, console
What is the purpose of module.exports in a Node.js module
Allows for Node.js to access whatever value that is assigned to the exports property in another node.
How do you import functionality into a Node.js module from another Node.js module?
using the require() function
What is the JavaScript event loop
a runtime that is specific to JavaScript, allows it to execute code, run and process events, and execute sub-queue tasks ; the thing that waits for the callstack to be cleared before pushing the things in the queue into the call stack
What is different between “blocking” and “non-blocking” with respect to how code is executed?
since javascript is a single thread language, when a process takes time, it prevents any other code from executing. non-blocking code would allow for other code to complete in a synchronous fashion.
What is a directory?
a location to store files
What is a relative file path?
the location of the file relative to another location/directory
What is an absolute file path?
the location of the file relative to the root directory
What module does Node.js include for manipulating the file system?
fs
What method is available in the Node.js fs module for writing data to a file?
writeFile() method
Are file operations using the fs module synchronous or asynchronous?
can be either or depending on the operation
Which HTTP method does a browser issue to a web server when you visit a URL?
GET
What is on the first line of an HTTP request message?
HTTP version, request target, http version
What is on the first line of an HTTP response message?
HTTP Version, status code, status message
What are HTTP headers?
additonal metadata about the server request or response
Is a body required for a valid HTTP message?
no
What is NPM?
Node packet manager - big software library , website-gui to browse registry, cli - command line client that talks to registry, registry (database)
What is a package?
file or module of js code that is reusable - a directory of files has at least one file, including a package.json file w/ metadata about the package
How can you create a package.json with npm?
go to the root of the directory you want to create a package.json in, and then use
‘npm -init’
What is a dependency and how to you add one to a package?
code you want to use but you didnt create, your code depends on it but you did not create it, using ‘npm install ‘package_name’’
prod dependencies - code that is used to help the code run
dev dependencies - code that doesn’t make it to the final product, it is used striclty for development (e.g. eslinter for
What happens when you add a dependency to a package with npm?
updates the package.json file, creates a node-modules folder (if it doesnt already exist ) and installs the package (in the directory you put it in)
How do you add express to your package dependencies?
npm install express
What Express application method starts the server and binds it to a network PORT?
listen method
How do you mount a middleware with an Express application?
use method of the app object
Whch objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
req and res