JavaScript Flashcards
What is the purpose of variables?
To temporarily store bits of information a script needs to do its job
How do you declare a variable?
set a variable name to a variable keyword like var
How do you initialize (assign a value to) a variable?
set a value to the variable name with an assignment operator = < > …
What characters are allowed in variable names?
letters, dollar sign or underscore, it cannot start with a number
What does it mean to say that variable names are “case sensitive”?
capitalization matters
What is the purpose of a string?
strings are data types that consist of letters and other characters, enclosed in quotes, frequently used to add new content to a page
What is the purpose of a number?
for numeric data and counting, calculating sums, measurements, time, etc.
What is the purpose of a boolean?
to indicate whether something is true or false
What does the = operator mean in JavaScript?
the equals operator assigns a value to a variable
How do you update the value of a variable?
use the variable name and equals sign to assign it a new value
What is the difference between null and undefined?
without setting a variable name to a variable keyword, the name will be null, without assigning a value to a variable, it will be undefined.
null is a nonexistent or invalid object
Why is it a good habit to include “labels” when you log values to the browser console?
to help you debug code, so you know which variable is being logged
Give five examples of JavaScript primitives.
null, string, number, boolean, undefined, symbol, bigint
What data type is returned by an arithmetic operation?
an expression?
What is string concatenation?
combining two strings into one
What purpose(s) does the + plus operator serve in JavaScript?
concatenation, addition, forcing a variable into a number, incrementing by one for a double plus
What data type is returned by comparing two values (, ===, etc)?
boolean
What does the += “plus-equals” operator do?
addition assignment, total += 1 would mean total = total + 1
What are objects used for?
storing multiple properties related to a variable
What are object properties?
variables that tell us about the object
Describe object literal notation.
an object’s properties and methods are assigned a variable name with the equals operator
How do you remove a property from an object?
delete object name . property name
What are the two ways to get or update the value of a property?
dot notation or square bracket with property in quotes
What are arrays used for?
a list of values that are related to each other
Describe array literal notation.
name a variable and assign it values within brackets, separated by commas
How are arrays different from “plain” objects?
because with arrays, the order matters. values are accessed by their numerical order
What number represents the first index of an array?
0
What is the length property of an array?
the length property calculated the total number of indexes in an array
How do you calculate the last index of an array?
.length - 1
What is a function in JavaScript?
Functions are a series of instructions to be carried out when called.
Describe the parts of a function definition.
functions begin with the function keyword, an optional name, (parameters, more, more, etc…), the function code block beginning with {, an optional return statement, and a closing } for the code block
Describe the parts of a function call.
a function call is initiated by the function name, parenthesis, and parameters.
When comparing them side-by-side, what are the differences between a function call and a function definition?
a function definition does not include arguments, only parameters
What is the difference between a parameter and an argument?
parameters are placeholders for future arguments
Why are function parameters useful?
They allow you to use the function more than once
What two effects does a return statement have on the behavior of a function?
- It produces a value we can use.
2. It prevents any more code from being run.
Why do we log things to the console?
to debug, to ensure our code is working properly, to test a function before pairing it with another element
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?
A method is specifically tied to or contained within a function, some are built in, and we can add our own methods to objects.
How do you remove the last element from an array?
.pop()
How do you round a number down to the nearest integer?
Math.floor()
How do you generate a random number?
Math.random()
How do you delete an element from an array?
with splice(), or shift()
How do you append an element to an array?
with push() - which puts it at the end of the array, or unshift() which puts it at the beginning of the array
How do you break a string up into an array?
with split() and an argument dictating where to split the array
Do string methods change the original string? How would you check if you weren’t sure?
no, you could console.log the original array after calling a method
Roughly how many string methods are there according to the MDN Web docs?
around 60
Is the return value of a function or method useful in every situation?
no, like pop
Roughly how many array methods are there according to the MDN Web docs?
40
What three-letter acronym should you always include in your Google search about a JavaScript method or CSS property?
MDN
Give 6 examples of comparison operators.
== , !=, >, =, <=, ===, !==
What data type do comparison expressions evaluate to?
boolean
What is the purpose of an if statement?
to check if the following code should continue running, to filter out edge cases, etc.
Is else required in order to use an if statement?
no
Describe the syntax (structure) of an if statement.
if keyword precedes the condition ( ) inside the condition are operands (values being compared) and an operator/s like < > ===, followed by opening curly brace for code block that will execute if condition is met ( or true )
What are the three logical operators?
and && or || not !
How do you compare two different expressions in the same condition?
by using and && or or ||
What is the purpose of a loop?
loops check a condition, if its true, the code block will run and then it’s checked again
What is the purpose of a condition expression in a loop?
to determine how many iterations a code will run
What does “iteration” mean in the context of loops?
how many times the code block runs
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?
the first time the code is run
When does the condition expression of a for loop get evaluated?
immediately after the initialization expression and again until the condition is met
When does the final expression of a for loop get evaluated?
after the loop and until the condition is met
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?
increment the counter by 1
How do you iterate through the keys of an object?
for in loop
Why is using !important considered bad practice?
It makes debugging more difficult by breaking the natural cascading in your stylesheets
Why do we log things to the console?
To check and debug code before continuing a function or passing values to other functions
What is a model
A facsimile, something that is representative of another thing, a prototype, an ideal, a platonic form
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 pages elements are objects or nodes that you can access and navigate
What is a DOM Tree?
The dom tree is a js element for an html element with it’s properties, elements, children
Give two examples of document methods that retrieve a single element from the DOM.
getElementById and querySelector
Give one example of a document method that retrieves multiple elements from the DOM at once.
getElementByClassName, getElementsByTagName, querySelectorAll
Why might you want to assign the return value of a DOM query to a variable?
if you want to use the same element more than once. For instance, if you want to alter its innerHTML and setAttribute and addEventListener
What console method allows you to inspect the properties of a DOM element object?
console.dir
Why would a tag need to be placed at the bottom of the HTML content instead of at the top?
1.If you have code in your JavaScript that alters HTML as soon as the JavaScript file loads, there won’t actually be any HTML elements available for it to affect yet, so it will seem as though the JavaScript code isn’t working, and you may get errors. 2.If you have a lot of JavaScript, it can visibly slow the loading of your page because it loads all of the JavaScript before it loads any of the HTML. When you place your JavaScript links at the bottom of your HTML body, it gives the HTML time to load before any of the JavaScript loads, which can prevent errors, and speed up website response time.
What does document.querySelector() take as its argument and what does it return?
a css selector, and it returns the first matching element
What does document.querySelectorAll() take as its argument and what does it return?
a css selector, and it returns all that match
Why do we log things to the console?
to debug and see what we’re doing
Are all possible parameters required to use a JavaScript method or function?
No? Just the object
What method of element objects lets you set up a function to be called when a specific type of event occurs?
addEventListener
What is the purpose of events and event handling?
Events are fired to notify code of “interesting changes” that may affect code execution. These can arise from user interactions such as using a mouse or resizing a window, changes in the state of the underlying environment (e.g. low battery or media events from the operating system), and other causes.
What is a callback function?
A callback function is 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?
an event type
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 is a reference to the object onto which the event was dispatched. The element of where the event occurred.
What is the difference between these two snippets of code?
the second one is pointless because there are no arguments, both will fire the handleClick, but the first is the better option because the handleClick function may take arguments?
What is the className property of element objects?
The className property of the Element interface gets and sets the value of the class attribute of the specified element.
How do you update the CSS class attribute of an element using JavaScript?
with the className property
What is the textContent property of element objects?
The textContent property of the Node interface represents the text content of the node and its descendants.
How do you update the text within an element using JavaScript?
.textContent =
Is the event parameter of an event listener callback always useful?
no, you can use an anonymous function right there and avoid it
Would this assignment be simpler or more complicated if we didn’t use a variable to keep track of the number of clicks?
more difficult
Why is storing information about a program in variables better than only storing it in the DOM?
by storing them in variables you can reuse them
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?
stop the form info from being sent
What does submitting a form without event.preventDefault() do?
the page refreshes
What property of a form element object contains all of the form’s controls.
elements
What property of form a 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 don’t know where it’s wrong
What is an advantage of having your console open when writing a JavaScript program?
you can use debugger and see what’s happening
Does the document.createElement() method insert a new element into the page?
No, not untill it’s appended
How do you add an element as a child to another element?
appendChild
What do you pass as the arguments to the element.setAttribute() method?
name, value
What steps do you need to take in order to insert a new element into the page?
createElement, createTextNode(optional), appendChild
create new element
store new element
query for parent element
call appendchild on parent with the new element as an argument
What is the textContent property of an element object for?
The textContent property of the Node interface represents the text content of the node and its descendants.
Name two ways to set the class attribute of a DOM element.
setAttribute with name, className
What are two advantages of defining a function to do create something (like the work of creating a DOM tree)?
You can give that code a name, it’s easier to test, easier to reuse elsewhere
What is the event.target?
the place where the event occurred
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?
element.tagname
What does the element.closest() method take as its argument and what does it return?
The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.
How can you remove an element from the DOM?
The Element.remove() method removes the element from the tree it belongs to.
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 it to the parent
What is the event.target?
where the event occurred
What does the element.matches() method take as an argument and what does it return?
The matches() method checks to see if the Element would be selected by the provided selectorString – in other words – checks if the element “is” the selector.
How can you retrieve the value of an element’s attribute?
element.getAttribute
At what steps of the solution would it be helpful to log things to the console?
after you query an element, and again after you create any new variable
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?
we’d have to query the tab directly with querySelector
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?
with a giant set of conditionals for each view
What is a method?
A method is a function attached to an object
How can you tell the difference between a method definition and a method call?
a method definition lives inside an object and precedes a colon, a method call precedes a dot and is followed by parenthesis
Describe method definition syntax (structure).
method: function (param) { return }
Describe method call syntax (structure).
object.method()
How is a method different from any other function?
A method belongs to an object
What is the defining characteristic of Object-Oriented Programming?
Objects containing data and code, and the this/self notation, instances, class-based
Methods are behavior for actions to be done.
What are the four “principles” of Object-Oriented Programming?
Abstraction, Encapsulation, Inheritance, Polymorphism
Encapsulation: In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components.[1] Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.
Publicly accessible methods are generally provided in the class to access or modify the state more abstractly. In practice sometimes methods (so-called “getters” and “setters”) are provided to access the values indirectly, but, although not necessarily a violation of abstract encapsulation, they are often considered a sign-post of potentially poor object-oriented programming (OOP) design practice [2] (an Anti-pattern).
Inheritance: In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation. Also defined as deriving new classes (sub classes) from existing ones such as super class or base class and then forming them into a hierarchy of classes. In most class-based object-oriented languages, an object created through inheritance, a “child object”, acquires all the properties and behaviors of the “parent object” , with the exception of: constructors, destructor, overloaded operators and friend functions of the base class. Inheritance allows programmers to create classes that are built upon existing classes,[1] to specify a new implementation while maintaining the same behaviors (realizing an interface), to reuse code and to independently extend original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a directed graph.
Polymorphism: In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types[1] or the use of a single symbol to represent multiple different types.[2]The concept is borrowed from a principle in biology where an organism or species can have many different forms or stages.[3]
What is “abstraction”?
Abstraction is being able to work with complex things in simple ways. The DOM is an abstraction of the html document, not the actual document.
the creation of abstract concept-objects by mirroring common features or attributes of various non-abstract objects or systems of study[3] – the result of the process of abstraction.
Abstraction, in general, is a fundamental concept in computer science and software development.[4] The process of abstraction can also be referred to as modeling and is closely related to the concepts of theory and design.[5] Models can also be considered types of abstractions per their generalization of aspects of reality.
What does API stand for?
Application Programming Interface
What is the purpose of an API?
To hide the internal details of how a system works, exposing only those parts a programmer will find particularly useful
What is this in JavaScript?
this is an implicit parameter of all javascript objects, this is the object you’re current’y working with
What does it mean to say that this is an “implicit parameter”?
it’s available in the function code-block even though it was never given as an argument
When is the value of this determined in a function; call time or definition time?
call time baby
What does this refer to in the following code snippet?
the character object
Given the above character object, what is the result of the following code snippet? Why?
nothing because it hasn’t been called yet
Given the above character object, what is the result of the following code snippet? Why?
It’s me, mario!
Because you just assigned a variable to the character method greet
How can you tell what the value of this will be for a particular function or method definition?
you can’t, it’s a parameter and it doesn’t have a value until called
How can you tell what the value of this is for a particular function or method call?
whatever the properties of the object it’s being called from, left of the dot
What kind of inheritance does the JavaScript programming language use?
Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented, classless, or instance-based programming.
What is a prototype in JavaScript?
generalized object that can be reused, cloned, extended, etc. Array prototypes are applied to every array.
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?
Because there are string, array, and number prototypes
If an object does not have it’s own property or method by a given key, where does JavaScript look for it?
the prototype
What does the new operator do?
The new keyword does the following things:
Creates a blank, plain JavaScript object.
Adds a property to the new object (__proto__) that links to the constructor function’s prototype object
Note: Properties/objects added to the construction function prototype are therefore accessible to all instances created from the constructor function (using new).
Binds the newly created object instance as the this context (i.e. all references to this in the constructor function now refer to the object created in the first step).
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
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.
What is a “callback” function?
A callback function is 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.
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?
setInterval setTimeout
How can you set up a function to be called repeatedly without using a loop?
setInterval
What is the default time delay if you omit the delay parameter from setTimeout() or setInterval()?
0
What do setTimeout() and setInterval() return?
the timeOutID
The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(). This value can be passed to clearTimeout() to cancel the timeout.
It is guaranteed that a timeoutID value will never be reused by a subsequent call to setTimeout() or setInterval() on the same object (a window or a worker). However, different objects use separate pools of IDs.
What is a client?
Client–server model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients.[1] Often clients and servers communicate over a computer network on separate hardware, but both client and server may reside in the same system. A server host runs one or more server programs, which share their resources with clients. A client usually does not share any of its resources, but it requests content or service from a server. Clients, therefore, initiate communication sessions with servers, which await incoming requests. Examples of computer applications that use the client–server model are email, network printing, and the World Wide Web.
https://en.wikipedia.org/wiki/Client%E2%80%93server_model
What is a server?
A server host runs one or more server programs, which share their resources with clients.
The “client-server” characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. Servers are classified by the services they provide. For example, a web server serves web pages and a file server serves computer files. A shared resource may be any of the server computer’s software and electronic components, from programs and data to processors and storage devices. The sharing of resources of a server constitutes a service.
Whether a computer is a client, a server, or both, is determined by the nature of the application that requires the service functions. For example, a single computer can run web server and file server software at the same time to serve different data to clients making different kinds of requests. Client software can also communicate with server software within the same computer.[2] Communication between servers, such as to synchronize data, is sometimes called inter-server or server-to-server communication.
Which HTTP method does a browser issue to a web server when you visit a URL?
GET (Post, Head Options)
to send data to the server/database, POST
What three things are on the start-line of an HTTP request message?
A start-line describing the requests to be implemented, or its status of whether successful or a failure. This start-line is always a single line.
An optional set of HTTP headers specifying the request, or describing the body included in the message.
A blank line indicating all meta-information for the request has been sent.
An optional body containing data associated with the request (like content of an HTML form), or the document associated with a response. The presence of the body and its size is specified by the start-line and HTTP headers.
What three things are on the start-line of an HTTP response message?
The protocol version, usually HTTP/1.1.
A status code, indicating success or failure of the request. Common status codes are 200, 404, or 302
A status text. A brief, purely informational, textual description of the status code to help a human understand the HTTP message.
What are HTTP headers?
HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon (:), then by its value. Whitespace before the value is ignored.
Where would you go if you wanted to learn more about a specific HTTP Header?
MDN on HTTP Headers
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
Is a body required for a valid HTTP request or response message?
The last part of a response is the body. Not all responses have one: 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.
Bodies can be broadly divided into three categories:
Single-resource bodies, consisting of a single file of known length, defined by the two headers: Content-Type and Content-Length.
Single-resource bodies, consisting of a single file of unknown length, encoded by chunks with Transfer-Encoding set to chunked.
Multiple-resource bodies, consisting of a multipart body, each containing a different section of information. These are relatively rare.
What is AJAX?
Ajax is a technique for loading data into part of a page without having to refresh the entire page. The data is often sent in a format called JavaScript Object Notation or JSON
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
var requestVariable = new XMLHttpRequest() requestVarialbe.open('GET', 'filepath.json', true) reqeustVariable.send ('search=pepperoni')
reponse
requestVariable.onload = function() {
}
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?
they both share a prototype
What is a code block? What are some examples of a code block?
function code block, if block, conditional code block, object code block
What does block scope mean?
the variable is contained within the block of code, it isn’t globally accessible, it’s only accessible within the code block
What is the scope of a variable declared with const or let?
They are both block scoped variables
What is the difference between let and const?
the variables declared by the const keyword cannot be reassigned
Why is it possible to .push() a new value into a const variable that points to an Array?
you can mutate the array, but you cannot reassign the variable to another array or something else entirely
How should you decide on which type of declaration to use?
If you’re going to be reassigning the value of a variable each iteration, like a loop and i, you should use let, otherwise use const
What is the syntax for writing a template literal?
a string with backticks instead of quotes
What is “string interpolation”?
String formatting: the ability to substitute part of the string for the values of variables or expressions. This feature is also called string interpolation.
What is destructuring, conceptually?
flattening the object literal structure and flipping it around so you can declare and assign properties/values before assigning the abject or array a variable name
What is the syntax for Object destructuring?
let { property: value, property: value} = variable name
What is the syntax for Array destructuring?
let [ variable, another variable, …] = function() that returns array
How can you tell the difference between destructuring and creating Object/Array literals?
destructuring is done in the opposite format and set equal to the object/array
What is the syntax for defining an arrow function?
function nam = (params) => return
When an arrow function’s body is left without curly braces, what changes in its functionality?
nothing
How is the value of this determined within an arrow function?
by the following surrounding scope
What is a CLI?
command line interface
What is a GUI?
graphical user interface
man
you need to find a specific command
cat
when you want to combine similar files into another directory
ls
when you need to see the contents of a directory
pwd
when you need the filepath
echo
prints a string
touch
when you want to make a new file
mkdir
when you want to make a new directory/folder
mv
renames or moves
rm
removes
cp
copies
What is Node.js?
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.
Node.js is similar in design to, and influenced by, systems like Ruby’s Event Machine and Python’s Twisted. Node.js takes the event model a bit further. It presents an event loop as a runtime construct instead of as a library. In other systems, there is always a blocking call to start the event-loop. Typically, behavior is defined through callbacks at the beginning of a script, and at the end a server is started through a blocking call like EventMachine::run(). In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.js exits the event loop when there are no more callbacks to perform. This behavior is like browser JavaScript — the event loop is hidden from the user.
HTTP is a first-class citizen in Node.js, designed with streaming and low latency in mind. This makes Node.js well suited for the foundation of a web library or framework.
What can Node.js be used for?
Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser. Consequently, Node.js represents a “JavaScript everywhere” paradigm,[6] unifying web-application development around a single programming language, rather than different languages for server-side and client-side scripts.
What is a REPL?
A read–eval–print loop (REPL), also termed an interactive toplevel or language shell, is a simple interactive computer programming environment that takes single user inputs, executes them, and returns the result to the user; a program written in a REPL environment is executed piecewise.[1] The term is usually used to refer to programming interfaces similar to the classic Lisp machine interactive environment. Common examples include command-line shells and similar environments for programming languages, and the technique is very characteristic of scripting languages.[2
When was Node.js created?
may 27 2009 by ryan dahl
What back end languages have you heard of?
Python
What is a computer process?
In computing, a process is the instance of a computer program that is being executed by one or many threads. It contains the program code and its activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that execute instructions concurrently.[1][2]
Roughly how many computer processes are running on your host operating system (Task Manager or Activity Monitor)?
528
Why should a full stack Web developer know that computer processes exist?
Full stack Web development is based on making multiple processes work together to form one application, so having at least a cursory awareness of computer processes is necessary. This will be extremely important when learning about applications made of multiple components, such as clients, servers, and databases.
so they know how much memory their application takes up, whether all threads are running concurrently, and which part of the application is causing issues (front or back end)
What is the process object in a Node.js program?
The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). It can also be explicitly accessed using require():
How do you access the process object in a Node.js program?
require ‘process’
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)
__dirname: directory name of current module, same as the path.dirname() of the __filename
\_\_filename The file name of the current module. This is the current module file's absolute path with symlinks resolved.
For a main program this is not necessarily the same as the file name used in the command line.
exports#
Added in: v0.1.12
A reference to the module.exports that is shorter to type. See the section about the exports shortcut for details on when to use exports and when to use module.exports.
module#
Added in: v0.1.16
A reference to the current module, see the section about the module object. In particular, module.exports is used for defining what a module exports and makes available through require().
require(id)# Added in: v0.1.13 id module name or path Returns: exported module content Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by \_\_dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems.
Give two examples of truly global variables in a Node.js program
Abort controller: A utility class used to signal cancelation in selected Promise-based APIs. The API is based on the Web API AbortController.
process object: The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). It can also be explicitly accessed using require():
what is the JavaScript Event Loop
JavaScript is single-threaded, meaning it can only execute one function at a time, but the event loop an dit’s queue/stack give the illusion that it’s multithreaded and non-blocking
the event loop pulls things (generally functions) out of the queue and places them onto the execution stack whenever the stack becomes empty, giving the illusion that javascript is multithreaded even though it is single threaded
so, when the stack executes setTimeOut, setTimeOut’s callback funciton is pushed into the web API where it waits. It’s then pushed to the queue were it waits until the stack is empty, then it’s pushed into the stack for execution.
what’s the difference between blocking and non-blocking?
blocking means nothing else can happen until it’s complete, non-blocking is like setTimeout or asynchronous functions that can execute in the order of the call stack, or the next time the event loop comes around and moves it out of the queue
non-blocking is synchronous execution of code, one after another regardless of time complexity
non-blocking means code can run asynchronously. With node, that means larger functions can be pushed into thread pools while smaller functions are handled by the event loop
What is a directory?
A directory is a folder
What is a relative file path?
A path that begins with the current directory
What is an absolute path?
A path that contains the root directory and all other subdirectories
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?
fs.writeFile is asynchronous, while fs.writeFileSync is synchronous aka it blocks the event loop
What is a client?
a service requester / browser
Client–server model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients.[1] Often clients and servers communicate over a computer network on separate hardware, but both client and server may reside in the same system. A server host runs one or more server programs, which share their resources with clients. A client usually does not share any of its resources, but it requests content or service from a server. Clients, therefore, initiate communication sessions with servers, which await incoming requests. Examples of computer applications that use the client–server model are email, network printing, and the World Wide Web.
What is a server?
The server component provides a function or service to one or many clients, which initiate requests for such services. Servers are classified by the services they provide. For example, a web server serves web pages and a file server serves computer files. A shared resource may be any of the server computer’s software and electronic components, from programs and data to processors and storage devices. The sharing of resources of a server constitutes a service.
Generally, a service is an abstraction of computer resources and a client does not have to be concerned with how the server performs while fulfilling the request and delivering the response. The client only has to understand the response based on the well-known application protocol, i.e. the content and the formatting of the data for the requested service.
Clients and servers exchange messages in a request–response messaging pattern. The client sends a request, and the server returns a response. This exchange of messages is an example of inter-process communication. To communicate, the computers must have a common language, and they must follow rules so that both the client and the server know what to expect. The language and rules of communication are defined in a communications protocol. All protocols operate in the application layer. The application layer protocol defines the basic patterns of the dialogue. To formalize the data exchange even further, the server may implement an application programming interface (API).[3] The API is an abstraction layer for accessing a service. By restricting communication to a specific content format, it facilitates parsing. By abstracting access, it facilitates cross-platform data exchange.[4]
A server may receive requests from many distinct clients in a short period of time. A computer can only perform a limited number of tasks at any moment, and relies on a scheduling system to prioritize incoming requests from clients to accommodate them. To prevent abuse and maximize availability, the server software may limit the availability to clients. Denial of service attacks are designed to exploit a server’s obligation to process requests by overloading it with excessive request rates. Encryption should be applied if sensitive information is to be communicated between the client and the server.
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?
GET / HTTP/1.1
What is on the first line of an HTTP response message?
HTTP/1.1 200 OK (if it’s okay)
What are HTTP headers?
Key value pairs.
HTTP headers from a request follow the same basic structure of an HTTP header: a case-insensitive string followed by a colon (‘:’) and a value whose structure depends upon the header. The whole header, including the value, consist of one single line, which can be quite long.
Is a body required for a valid HTTP message?
Not all requests have one: requests fetching resources, like GET, HEAD, DELETE, or OPTIONS, usually don’t need one. Some requests send data to the server in order to update it: as often the case with POST requests (containing HTML form data).
What is NPM?
npm is the world’s largest software registry. Open source developers from every continent use npm to share and borrow packages, and many organizations use npm to manage private development as well.
npm consists of three distinct components:
the website
the Command Line Interface (CLI)
the registry
Use the website to discover packages, set up profiles, and manage other aspects of your npm experience. For example, you can set up organizations to manage access to public or private packages.
The CLI runs from a terminal, and is how most developers interact with npm.
The registry is a large public database of JavaScript software and the meta-information surrounding it.
Use npm to . . .
Adapt packages of code for your apps, or incorporate packages as they are.
Download standalone tools you can use right away.
Run packages without downloading using npx.
Share code with any npm user, anywhere.
Restrict code to specific developers.
Create organizations to coordinate package maintenance, coding, and developers.
Form virtual teams by using organizations.
Manage multiple versions of code and code dependencies.
Update applications easily when underlying code is updated.
Discover multiple ways to solve the same puzzle.
Find other developers who are working on similar problems and projects.
What is a package?
A package is a file or directory that is described by a package.json file. A package must contain a package.json file in order to be published to the npm registry. For more information on creating a package.json file, see “Creating a package.json file”.
Packages can be unscoped or scoped to a user or organization, and scoped packages can be private or public.
About package formats
A package is any of the following:
a) A folder containing a program described by a package.json file.
b) A gzipped tarball containing (a).
c) A URL that resolves to (b).
d) A @ that is published on the registry with (c).
e) A @ that points to (d).
f) A that has a latest tag satisfying (e).
g) A git url that, when cloned, results in (a).
How can you create a package.json with npm?
npm init
What is a dependency and how to you add one to a package?
packages your project depends on, listed as “dependencies” in your package.json file or “devDependencies”
to add dependencies to a package.json under devDependencies, you use the command line and do:
npm install –save-dev
What happens when you add a dependency to a package with npm?
npm will download that dependency when you run npm install, or whenever your package runs
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
How do you mount a middleware with an Express application?
.use method
Which objects does an Express application pass to your middleware to manage the request/response lifecycle of the server?
req res
What is the appropriate Content-Type header for HTTP messages that contain JSON in their bodies?
application/json
what is the significance of the HTTP request method
it tells you what the client is asking for/doing
what is express.json()
express.json() parses incoming json, .json() converts outgoing objects into json
What is PostgreSQL and what are some alternative relational databases?
A relational database is a digital database based on the relational model of data, as proposed by E. F. Codd in 1970.[1] A system used to maintain relational databases is a relational database management system (RDBMS). Many relational database systems have an option of using the SQL (Structured Query Language) for querying and maintaining the database.[2]
the relational model organizes into columns and rows, with a unique key identifying each row
Oracle Database IBM Db2 Microsoft SQL Server Microsoft Access SAP
As is typical of client/server applications, the client and the server can be on different hosts. In that case they communicate over a TCP/IP network connection. You should keep this in mind, because the files that can be accessed on a client machine might not be accessible (or might only be accessible using a different file name) on the database server machine.
The PostgreSQL server can handle multiple concurrent connections from clients. To achieve this it starts (“forks”) a new process for each connection. From that point on, the client and the new server process communicate without intervention by the original postgres process. Thus, the supervisor server process is always running, waiting for client connections, whereas client and associated server processes come and go. (All of this is of course invisible to the user. We only mention it here for completeness.)
What are some advantages of learning a relational database?
They can make it easy to access, organize, and protect data
What is one way to see if PostgreSQL is running?
sudo service postgresql status
What is a table?
A table is a list of rows each having the same set of attributes
What is a row?
The values for each row correspond to the attribute names
What is SQL and how is it different from languages like JavaScript?
SQL is a declarative programming language. In declarative languages, programmers describe the results they want and the programming environment comes up with its own plan for getting those results.
How do you retrieve specific columns from a database table?
with a select statement
How do you filter rows based on some specific criteria?
The query starts with the select keyword.
The select keyword is followed by a comma-separated list of column names, each surrounded by “ double quotes.
The column names are followed by a from clause specifying which table to retrieve the data from.
The query must end in a ; semicolon.
SQL keywords such as select and from are not case-sensitive.
SQL does not have to be indented, but you should do it anyway for consistent style and therefore readability.
How do you filter rows based on some specific criteria?
where “category” = ‘somecategory’;
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?
limit #;
How do you retrieve all columns from a database table?
select *
How do you control the sort order of a result set?
order by ____ desc; or asc;
How do you add a row to a SQL table?
an insert statement
What is a tuple?
a turple is a set/batch of values
How do you add multiple rows to a SQL table at once?
by using multiple turples, parenthetical sets of values
How do you get back the row being inserted into a table without a separate select statement?
with returning *;
How do you update rows in a database table?
with the update clause
Why is it important to include a where clause in your update statements?
so you can be specific about what you’re updating and not update everything
How do you delete rows from a database table?
with a delete clause
How do you accidentally delete all rows from a table?
you don’t specify rows or columns
What is a foreign key?
a column that’s shared between two tables
How do you join two SQL tables?
with a join clause
select *
from “products”
join “suppliers” using (“supplierId”);
How do you temporarily rename columns or tables in a SQL statement?
alias column names
What are some examples of aggregate functions?
max(), avg(), min(), sum(), every(),
select max(“price”) as “highestPrice” from “products”
select avg(“price”) as “averagePrice” from “products”
select count(*) as “totalProducts” from “products”
What is the purpose of a group by clause?
so you can specify certain rows, not the entire table
What are the three states a Promise can be in?
pending: initial state, neither fulfilled nor rejected.
fulfilled: meaning that the operation was completed successfully.
rejected: meaning that the operation failed.
How do you handle the fulfillment of a Promise?
with resolve
How do you handle the rejection of a Promise?
with reject
What is map useful for
for creating a new array from specific elements
What is Array.prototype.reduce useful for?
Combining the elements of an array into a single value.
What is “syntactic sugar”?
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.
For example, many programming languages provide special syntax for referencing and updating array elements. Abstractly, an array reference is a procedure of two arguments: an array and a subscript vector, which could be expressed as get_array(Array, vector(i,j)). Instead, many languages provide syntax such as Array[i,j]. Similarly an array element update is a procedure consisting of three arguments, for example set_array(Array, vector(i,j), value), but many languages provide syntax such as Array[i,j] = value.
A construct in a language is syntactic sugar if it can be removed from the language without any effect on what the language can do: functionality and expressive power will remain the same.
Language processors, including compilers and static analyzers, often expand sugared constructs into more fundamental constructs before processing, a process sometimes called “desugaring”.
What is the typeof an ES6 class?
a function
Describe ES6 class syntax.
class VariableName { constructor(variable) { this.variable = variable } methods() { return this.whatever }
This Person class behaves like the Person type in the previous example. However, instead of using a constructor/prototype pattern, it uses the class keyword.
In the Person class, the constructor() is where you can initialize the properties of an instance. JavaScript automatically calls the constructor() method when you instantiate an object of the class.
What is “refactoring”?
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior. Refactoring is intended to improve the design, structure, and/or implementation of the software (its non-functional attributes), while preserving its functionality. Potential advantages of refactoring may include improved code readability and reduced complexity; these can improve the source code’s maintainability and create a simpler, cleaner, or more expressive internal architecture or object model to improve extensibility. Another potential goal for refactoring is improved performance; software engineers face an ongoing challenge to write programs that perform faster or use less memory.
Typically, refactoring applies a series of standardised basic micro-refactorings, each of which is (usually) a tiny change in a computer program’s source code that either preserves the behaviour of the software, or at least does not modify its conformance to functional requirements. Many development environments provide automated support for performing the mechanical aspects of these basic refactorings. If done well, code refactoring may help software developers discover and fix hidden or dormant bugs or vulnerabilities in the system by simplifying the underlying logic and eliminating unnecessary levels of complexity. If done poorly, it may fail the requirement that external functionality not be changed, and may thus introduce new bugs.
By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you’ll find that it is easier to extend and maintain code.
— Joshua Kerievsky, Refactoring to Patterns[1]
What is Webpack?
Wouldn't it be nice… ...to have something that will not only let us write modules but also support any module format (at least until we get to ESM) and handle resources and assets at the same time?
This is why webpack exists. It’s a tool that lets you bundle your JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts and stylesheets.
Webpack cares about performance and load times; it’s always improving or adding new features, such as async chunk loading and prefetching, to deliver the best possible experience for your project and your users.
How do you add a devDependency to a package?
npm install package name –save-dev
What is an NPM script?
The “scripts” property of your package.json file supports a number of built-in scripts and their preset life cycle events as well as arbitrary scripts. These all can be executed by running npm run-script or npm run for short. Pre and post commands with matching names will be run for those as well (e.g. premyscript, myscript, postmyscript). Scripts from dependencies can be run with npm explore – npm run .
How are ES Modules different from CommonJS modules?
Being built into the language allows ES6 modules to go beyond CommonJS and AMD (details are explained later):
Their syntax is even more compact than CommonJS’s.
Their structure can be statically analyzed (for static checking, optimization, etc.).
Their support for cyclic dependencies is better than CommonJS’s.
The ES6 module standard has two parts:
Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules
If you require a library in CommonJS, you get back an object:
var lib = require('lib'); lib.someFunc(); // property lookup Thus, accessing a named export via lib.someFunc means you have to do a property lookup, which is slow, because it is dynamic.
In contrast, if you import a library in ES6, you statically know its contents and can optimize accesses:
import * as lib from ‘lib’;
lib.someFunc(); // statically resolved
With a static module structure, you always statically know which variables are visible at any location inside the module:
Global variables: increasingly, the only completely global variables will come from the language proper. Everything else will come from modules (including functionality from the standard library and the browser). That is, you statically know all global variables.
Module imports: You statically know those, too.
Module-local variables: can be determined by statically examining the module.
What kind of modules can Webpack support?
ECMAScript modules CommonJS modules AMD modules Assets WebAssembly modules
What is React?
React is a Javascript Framework/library that makes it easy to make reusable components that encapsulate html and logic into a class or function
Makes it easy to build modular applications
We can finally stop making giant DOM trees
What is a React element?
Elements are the smallest building blocks of react apps. A react element describes what you want to see on the screen. Unlike browser dom elements, react elements are plain object and are cheap to create. React dom takes care of updating the dom to match the react elements. Elements are what components are made of.
How do you mount a React element to the DOM?
By using ReactDOM.render, which is only called when the element changes
React DOM compares the element and its children to the previous one and only applies DOM updates necessary to bring the hhhhhhhhhhDOM to the desired state
What is Babel?
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:
Transform syntax
Polyfill features that are missing in your target environment (through a third-party polyfill such as core-js)
Source code transformations (codemods)
And more! (check out these videos for inspiration)
What is a Plug-in?
A software component that adds a specific feature to an existing program, often supporting customization. Like a theme or skin preset package that can change the GUI.
What is a Webpack loader?
Loaders are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!
How can you make Babel and Webpack work together?
npm install -D babel-loader @babel/core @babel/preset-env webpack
What is JSX?
A syntax extension of javascript
Fundamentally, JSX just provides syntactic sugar for the React.createElement(component, props, …children) function.
Why must the React object be imported when authoring JSX in a module?
Since JSX compiles into calls to React.createElement, the React library must also always be in scope from your JSX code.
How can you make Webpack and Babel work together to convert JSX into valid JavaScript?
‘@babel/plugin-transform-react-jsx’
What is a React component?
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components. You can find a detailed component API reference here.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
How do you define a function component in React?
the same way you do for a javascript function with props as a parameter and returning jsx
How do you mount a component to the DOM?
you create an element out of your function, then use reactdom.render and pass in the element along with document.querySelector(“#root”)
What are controlled components?
In HTML, form elements such as , , and typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState().
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
What two props must you pass to an input for it to be “controlled”?
onChange/Value
What Array method is commonly used to create a list of React elements?
map
What is the best value to use as a “key” prop when rendering lists?
id
what does express.static() do?
This is a built-in middleware function in Express. It serves static files and is based on serve-static.
The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it instead calls next() to move on to the next middleware, allowing for stacking and fall-backs.
what is the local __dirname variable in a Node.js module?
The directory name of the current module. This is the same as the path.dirname() of the __filename.
What does the join() method of Node’s path module do?
…paths A sequence of path segments
Returns:
The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a zero-length string then ‘.’ will be returned, representing the current working directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf'
path.join('foo', {}, 'bar'); // Throws 'TypeError: Path must be a string. Received {}'
What does fetch() return?
a promise
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.
The fetch specification differs from jQuery.ajax() in the following significant ways:
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn’t in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.
fetch() won’t send cross-origin cookies unless you set the credentials init option. (Since April 2018. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)
What is the default request method used by fetch()?
GET?
How do you specify the request method (GET, POST, etc.) when calling fetch?
const fetchResponsePromise = fetch(resource [, init])
When does React call a component’s componentDidMount method?
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
Name three React.Component lifecycle methods.
ComponentWillUnmount, ComponentDidMount, Render, ComponentDidUpdate
How do you pass data to a child component?
via props
What are closures?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
What must the return value of myFunction be if the following expression is possible?
myFunction()();
the return value must be a function
What does this code do? const wrap = value => () => value;
the function wrap is being defined with one argument, value, which return an anonymous function. The anonymous function returns the argument value
In JavaScript, when is a function’s scope determined; when it is called or when it is defined?
defined
What allows JavaScript functions to “remember” values from their surroundings?
the lexical scope - the location where the variable is declared. nested functions have access to outer functions variables, but not the other way around