Javascript Flashcards
What is the purpose of variables?
To store some sort of value
How do you declare a variable?
var varName = value;
How do you initialize (assign a value to) a variable?
varName = newValue;
What characters are allowed in variable names?
Letters, numbers, underscore, $dollar_sign
What does it mean to say that variable names are “case sensitive”?
“THIS” is different from “this” and “tHiS”
What is the purpose of a string?
To represent letters and characters
What is the purpose of a number?
To represent numerical data
What is the purpose of a boolean?
Used as a trigger for a condition
What does the = operator mean in JavaScript?
It’s the assignment operator
How do you update the value of a variable?
Assign a new value on the right side of the = operator
What is the difference between null and undefined?
null points to a nonexistent address
Undefined is a value for variables not yet defined
Why is it a good habit to include “labels” when you log values to the browser console?
It helps you recognize why you are logging onto the console
Give five examples of JavaScript primitives.
Number, string, boolean, array, object
What data type is returned by an arithmetic operation?
number
What is string concatenation?
Joining two or more strings together
What purpose(s) does the + plus operator serve in JavaScript?
String concatenation, addition for numbers
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
Adds the given value and re-assigns the new value to the variable on the left hand side of the operator
What are objects used for?
A data type that groups together a set of variables and functions to model real life ‘objects’
What are object properties?
Variables that hold data unique to that object
Describe object literal notation.
Declared with var objName = { }; Properties are stored between curly braces separated by commas
How do you remove a property from an object?
delete obj.prop;
What are the two ways to get or update the value of a property?
Dot notation and bracket notation with assignment operator
What are arrays used for?
To store related data in an ordered list
Describe array literal notation.
Declare with var arrName
Assign: [val1, val2, …];
How are arrays different from “plain” objects?
You access its elements using indices
What number represents the first index of an array?
0
What is the length property of an array?
It returns the length of an array or how many elements that array contains
How do you calculate the last index of an array?
arr.length - 1
What is a function in JavaScript?
To pack code for reuse throughout a program
Describe the parts of a function definition.
Function keyword, functionName(optional), parameters(optional), {code block}, return value(optional)
Describe the parts of a function call.
Function name and argument(s)
When comparing them side-by-side, what are the differences between a function call and a function definition?
Function call doesn’t have the actual code, the function definition has the ‘function’ keyword
What is the difference between a parameter and an argument?
Parameters are defined in the function definition, arguments are passed in a function call
Why are function parameters useful?
They can be used to store data to be used (and sometimes modified) within a function
What two effects does a return statement have on the behavior of a function?
It exits a function immediately
It pushes a value out to where the function is called
Why do we log things to the console?
To keep track of the changes we make to our code and verifies our data. This prevents hard to find bugs because we’ll see it immediately with the log
What is a method?
Functions that are properties of an object
How is a method different from any other function?
Functions can only be called from an object through dot operator
How do you remove the last element from an array?
arr.pop();
How do you round a number down to the nearest integer?
Math.floor(num)
How do you generate a random number?
Math.random()
How do you delete an element from an array?
arr.splice(startIndex, deleteCount)
How do you append an element to an array?
arr.push(elem);
How do you break a string up into an array?
aString.split(‘delimiter’)
Do string methods change the original string? How would you check if you weren’t sure?
Strings are immutable meaning they cannot be changed. Log to console if you aren’t sure
Roughly how many string methods are there according to the MDN Web docs?
About 35 not including ‘deprecated’ methods (not recommended to use because some browsers won’t support)
Is the return value of a function or method useful in every situation?
No, pop() will return a value, but you don’t need to use it
Roughly how many array methods are there according to the MDN Web docs?
About 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
What is the purpose of an if statement?
To evaluate the boolean value of a conditional expression
Is else required in order to use an if statement?
No
Describe the syntax (structure) of an if statement.
If keyword, conditional statement between parentheses, code block to run if “if” statement is true
What are the three logical operators?
&& and, || or, ! logical not
How do you compare two different expressions in the same condition?
Use a logical operator between the two expressions
What is the purpose of a loop?
To run a block of code multiple times
What is the purpose of a condition expression in a loop?
To check if the loops should advance or not
What does “iteration” mean in the context of loops?
A single pass of the code block
When does the condition expression of a while loop get evaluated?
Before each iteration
When does the initialization expression of a for loop get evaluated?
Before the condition expression is checked for the first time
Only gets initialized once
When does the condition expression of a for loop get evaluated?
After initialization and before the block of code runs
Subsequent loops, the condition expression is evaluated after the final (updating) expression
When does the final expression of a for loop get evaluated?
At the end of each iteration
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?
Adds 1 to the variable and reassigns it back into the variable
How do you iterate through the keys of an object?
By using a for..in loop
What event is fired when a user places their cursor in a form control?
focus
What event is fired when a user’s cursor leaves a form control?
blur
What event is fired as a user changes the value of a form control?
input
What event is fired when a user clicks the “submit” button within a ?
submit
What does the event.preventDefault() method do?
prevents the browser from automatically reloading the page with the form’s values in the URL
What does submitting a form without event.preventDefault() do?
Reloads the page
What property of a form element object contains all of the form’s controls.
Elements (?)
What property of a form control object gets and sets its value?
value
What is one risk of writing a lot of code without checking to see if it works so far?
You might miss a hard-to-find bug further down the line
What is an advantage of having your console open when writing a JavaScript program?
To check for bugs or mistakes while writing
What is the event.target?
It references the object in which the event was directed at
What is the effect of setting an element to display: none?
It hides the element from view on the screen
What does the element.matches() method take as an argument and what does it return?
It takes a selector (string) as an argument and it returns boolean value (true if it matches)
How can you retrieve the value of an element’s attribute?
element.getAttribute(‘attributeName’)
Returns the value attached to the attribute
At what steps of the solution would it be helpful to log things to the console?
Pretty much each step logging to the console would be useful
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 query each new tab and view DOM element and add an event listener to each one
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 have to write a stack of “if” and “else if” statements
What is JSON?
It stands for JavaScript Object Notation
It is a text-based data format which allows transmitting of data across networks
What are serialization and deserialization?
Serialization is converting a native object into a string for transmitting the data
Deserialization is the opposite of that
Why are serialization and deserialization useful?
It allows the transmitting and translating of data that, for the most part, can’t be transmitted
How do you serialize a data structure into a JSON string using JavaScript?
JSON.stringify(jsonObj)
How do you deserialize a JSON string into a data structure using JavaScript?
JSON.parse(jsonStr) const jsonStr = ‘{ “prop”:”value” }’; // quotes around prop required
How do you store data in localStorage?
window.localStorage.setItem( ‘prop-name’ , ‘jsonString’ )
How do you retrieve data from localStorage?
window.localStorage.getItem( ‘prop-name’ )
What data type can localStorage save in the browser?
JSON string
When does the ‘beforeunload’ event fire on the window object?
Before everything is unloaded
What is a method?
A function that is a property of an object
How can you tell the difference between a method definition and a method call?
A definition will have a block of code after the method’s name
Describe method definition syntax (structure).
objectName = {
methodName: function (para) { return something } };
Describe method call syntax (structure).
objectName.methodName(arguments);
How is a method different from any other function?
A method can only be called on the object it is associated with
What is the defining characteristic of Object-Oriented Programming?
The object
What are the four “principles” of Object-Oriented Programming?
Abstraction, encapsulation, inheritance, polymorphism
What is “abstraction”?
The process of taking a complex component of an object and making it more simplified to utilize its features
What does API stand for?
Application programming interface
What is the purpose of an API?
To allow users to utilize the abstraction of software & to share the functionality of a program
What is this in JavaScript?
An implicit parameter of all JS functions or the object itself or the global window object when not attached explicitly to an object
What does it mean to say that this is an “implicit parameter”?
It’s available in a function’s code block even when it’s not explicitly stated
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 character object
Given the above character object, what is the result of the following code snippet? Why?
character.greet();
It’s-a-me, Mario!
this.firstName refers to the character object when calling the greet method
Given the above character object, what is the result of the following code snippet? Why? var hello = character.greet; hello();
‘It’s-a-me, undefined!’
How can you tell what the value of this will be for a particular function or method definition?
The value of ‘this’ will be determined at function/method call depending if it has something to the left of the dot operator
How can you tell what the value of this is for a particular function or method call?
It will reference the object that is on the left of the dot operator. If there isn’t one, it will reference the global window object.
What kind of inheritance does the JavaScript programming language use?
prototypal
What is a prototype in JavaScript?
An object that contains properties that other objects can use
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?
These methods are defined on a prototype object and then set to be used by strings, arrays, and numbers
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
JS looks to see if it has a prototype property set in the prototype chain
What does the new operator do?
It creates an instance of a user-defined object
Adds a property to the object (__proto__)
‘This’ now refer to the object created
Returns ‘this’ if function doesn’t return an object
What property of JavaScript functions can store shared behavior for instances created with new?
The prototype property
What does the instanceof operator do?
Returns a boolean if “var” is an instance created by a constructor of an object
What is a “callback” function?
A function passed into another function as an argument
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(cbFn, delay);
How can you set up a function to be called repeatedly without using a loop?
setInterval(cbFn, delay);
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0 or immediately
What do setTimeout() and setInterval() return?
A timeout ID to store the timer’s ID. It can be used as an argument for clearTimeout()/clearInterval()
What is a client?
A computer or program that sends requests to access services available from servers
What is a server?
Hardware or software that provides functionality for other programs or devices after a request
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, request target, HTTP version
What three things are on the start-line of an HTTP response message?
Protocol version (usually HTTP/1.1) Status code (200, 404, 302, etc) Status text (OK, NOT FOUND, etc)
What are HTTP headers?
Text appearing on top of request or response messages showing information about the HTTP message
Where would you go if you wanted to learn more about a specific HTTP Header?
mdn/HTTP/messages
Is a body required for a valid HTTP request or response message?
No, responses with a status code that sufficiently answers the request without the need for corresponding payload (like 201 Created or 204 No Content) usually don’t.
What is AJAX?
A technique for loading data into a part of a page without having to refresh the entire page
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
Bonus Question: An XMLHttpRequest object has an addEventListener() method just like DOM elements. How is it possible that they both share this functionality?
The each share the prototype method (hidden 4 levels into the prototype chain)
What is a code block? What are some examples of a code block?
A section of code contained between {curly braces}
ex/ the code that is run after after a for loop statement
What does block scope mean?
It means that the variable that is declared is only visible within the code block
What is the scope of a variable declared with const or let?
Block scope
What is the difference between let and const?
Variables declared with let are mutable, const variables are not
Why is it possible to .push() a new value into a const variable that points to an Array?
Because the value stored in an array variable is the address in which it is pointing to therefore the elements
How should you decide on which type of declaration to use?
Let & const if you want the variable to be block scope. Const if you want the variable to be constant/immutable
What is destructuring, conceptually?
It is a way to fetch elements stored inside of an array or object
What is the syntax for Object destructuring?
The object variable on right side of assignment operator (=)
const, then the variables to store that data on left side inside curly braces
If variables do not share the same property names, you need to put the variable names on right side of property name separated by a colon
What is the syntax for Array destructuring?
The array variable on right side of assignment operator (=)
const, then the variables to store the array elements on left side inside square brackets
How can you tell the difference between destructuring and creating Object/Array literals?
When destructuring, the object/array is on the right side of the assignment operator (=)
What is the syntax for writing a template literal?
Template literals are surrounded by backticks and an interpolated expressions begin with $ and curly braces around the expression
What is “string interpolation”?
It is a way to represent strings that are inserted into an expression not defined as a string
What is the syntax for defining an arrow function?
(param1, param2) => { code block }
If there is only 1 parameter, parentheses are not needed
If code block doesn’t have a statement, curly braces are not needed
When an arrow function’s body is left without curly braces, what changes in its functionality?
It implicitly returns the statement inside of the code block
How is the value of this determined within an arrow function?
It doesn’t define its own ‘this’ value but rather it captures the ‘this’ value from the enclosing context
What is a CLI?
Command Line Interface
What is a GUI?
Graphical User Interface
What are the three virtues of a great programmer?
Laziness, impatience, hubris
What is Node.js?
A JavaScript runtime environment
What can Node.js be used for?
It can be used to execute JS code outside of a browser
What is a REPL?
read–eval–print loop
A interactive computer programming environment that allows a single user to input code, execute it and the REPL returns the result
When was Node.js created?
May 27, 2009
What back end languages have you heard of?
Express, Django, Flask, Ruby on Rails, PHP, python, perl
What is a computer process?
An instance of a computer program running
Roughly how many computer processes are running on your host operating system (Task Manager or Activity Monitor)?
I currently have about 200 process running according to my Task Manager
Why should a full stack Web developer know that computer processes exist?
A full-stack app or program requires multiple processes to work together so understanding processes lets the developer recognize how each piece can perform cohesively and to properly allocated resources to help load balance the server
What is the process object in a Node.js program?
It is a global object that provides information and control over the current Node.js process
How do you access the process object in a Node.js program?
You can handle the process object using its properties
What is the data type of process.argv in Node.js?
Array of strings
What is a JavaScript module?
A single JS file
What values are passed into a Node.js module’s local scope?
Exports, require, module, __filename, __dirname
Give two examples of truly global variables in a Node.js program.
Console, process
What is the purpose of module.exports in a Node.js module?
To export the module into another file. Typically into a file that will use that module
How do you import functionality into a Node.js module from another Node.js module?
Const variable = require(‘./fileName)
fileName can be written with .js at end, but it is implied
What is the JavaScript Event Loop?
It is the queue in which messages are ran
What is the difference between “blocking” and “non-blocking” with respect to how code is executed?
Code is blocking if the event loops is being stopped because of that code
What is a directory?
A folder containing files
What is a relative file path?
It refers to the location in which a file is found relative to the current directory
What is an absolute file path?
It refers to the location that contains the root directory
What module does Node.js include for manipulating the file system?
fs (file system)
What method is available in the Node.js fs module for writing data to a file?
fs.writeFile()
Are file operations using the fs module synchronous or asynchronous?
asynchronous
What is a client?
A computer or program that sends requests to access services available from servers
What is a server?
Hardware or software that provides functionality for other programs or devices after a request
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 method, request target, HTTP version
What is on the first line of an HTTP response message?
Protocol version (usually HTTP/1.1) Status code (200, 404, 302, etc) Status text (OK, NOT FOUND, etc)
What are HTTP headers?
Text appearing on top of request or response messages showing information about the HTTP message
Is a body required for a valid HTTP message?
No, responses with a status code that sufficiently answers the request without the need for corresponding payload (like 201 Created or 204 No Content) usually don’t.
What is NPM?
Stands for nose-picking-monkeys
It is a package managing tool by node that allows users to download and install packages to use
What is a package?
A library of code created by people that are available to be used from npm
How can you create a package.json with npm?
npm init –yes
What is a dependency and how do you add one to a package?
A third-party piece of software used to solve a single problem
npm install nameOfPackage
What happens when you add a dependency to a package with npm?
It gets added to the list of “dependencies” in package.json and
A directory holding the dependency is added to ‘node_modules’
How do you add express to your package dependencies?
Initialize package.json, install express
What Express application method starts the server and binds it to a network PORT?
listen()
How do you mount a middleware with an Express application?
With app.use() method
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
Request object & response object
What is the appropriate Content-Type header for HTTP messages that contain JSON in their bodies?
application/json
What is the significance of an HTTP request’s method?
To clearly indicate the desired action to be performed
But there is little to no significance since the method written is only there for semantics because the code block can be written in any way
What does the express.json() middleware do and when would you need it?
It parses incoming requests that are structured as JSON objects.
What is PostgreSQL and what are some alternative relational databases?
A relational database management system
MySQL, SQL Server, Oracle
What are some advantages of learning a relational database?
Guarantees data integrity, widely used, portable skill to have
What is one way to see if PostgreSQL is running?
‘sudo service postgresql status’ or ‘top’
What is a database schema?
A collection of tables
Sometimes refer to blueprints for building a table
What is a table?
A set of data elements organized in columns and rows
What is a row?
A data entry that shows the values for each attribute
What is SQL and how is it different from languages like JavaScript?
It’s a language used to interact with relational databases.
How do you retrieve specific columns from a database table?
Select “specific column” from “table”
How do you filter rows based on some specific criteria?
Where (condition)
Like “age” > 10
What are the benefits of formatting your SQL?
Readability and consistency
What are four comparison operators that can be used in a where clause?
=, , !=
How do you limit the number of rows returned in a result set?
At the end of your query, you add “limit x” x is the number of rows to limit
How do you retrieve all columns from a database table?
Select * from “table”
How do you control the sort order of a result set?
After: from “table” ⇒ order by “column”
desc for descending order
How do you add a row to a SQL table?
Use insert into keywords “tableName” Values keyword (“value1”, “value2”)
What is a tuple?
A finite ordered list of values
How do you add multiple rows to a SQL table at once?
After the values keyword, each tuple is separated by a comma
How do you get back the row being inserted into a table without a separate select statement?
After the values, use the returning clause
How do you delete rows from a database table?
‘delete by’ keywords
How do you accidentally delete all rows from a table?
By omitting the where clause that includes a conditional
What is a foreign key?
A relational attribute that can be used to join 2 or more tables together
How do you join two SQL tables?
JOIN “table” USING (“attribute”)
How do you temporarily rename columns or tables in a SQL statement?
Using an alias with the ‘AS’ keyword
What are some examples of aggregate functions?
Max, avg, count, sum
What is the purpose of a group by clause?
To groups a collection of rows to perform aggregate functions on those rows
What are the three states a Promise can be in?
Pending, fulfilled, rejected
How do you handle the fulfillment of a Promise?
Call the then() method
How do you handle the rejection of a Promise?
Call the catch() method