Javascript Conceptual (Node, Express, React, Redux, JS)

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What are some differences between arrow functions and the function keyword?

- Arrow functions have a shorter syntax - Arrow functions have an implicit `return` if their function body is a single expression - Arrow functions don't get their own `arguments` keyword - Arrow functions don't get their own `this` keyword

What are some differences between `let` and `const`?*

- `let` variables can be reassigned, `const` variables cannot.

What are some differences between `var` and `let`?

- variables declared with `let` are scoped to the nearest function or block; var declarations are globally scoped or function/locally scoped. The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window. var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function. variables declared with `var` are only function scoped. - you can redeclare variables with `var`, but not `let`.

What happens if you forget the `async` keyword on the declaration of a function that uses `await` inside of it?

A SyntaxError will be thrown so make sure you always use the `async` keyword when defining a function that needs to use the `await` keyword.

How is a Component created in React?

A component is a class that is extended from the React.Component class. This class knows how to render itself.

What is a controlled component?

A controlled component is one that is controlled by react and that state is always controlled by react. For example, in an input field in a form when the input is text react should control the state of the input so that it can use it. There could be issues if react is not aware of the changes being made in the DOM when compared to it's virtual DOM.

What is a jQuery object?

A jQuery object is not an HTML object. It is an object that is specific to jQuery that you can perform actions specific to jQuery such as parent(). This jQuery object can however be inserted into the DOM as an HTML object. It is frequently the returned value of jQuery methods so that it can be chained - `$("h1").text("awesome").css("color","red").attr("id","main-heading")` etc.

What are React hooks?

A newer way to introduce state and lifecycle behavior to functional components

What is the error-first callback pattern?

A pattern where Node callbacks will have the error as the first parameter. This is common with older modules that do not support promises or async/await

What is a Promise?

A promise is a one time guarantee of future value. This means that a promise will either be rejected or resolved with a value and that is guaranteed to happen in the future at some point.

What is a reducer?

A reducer is a function that accepts a state and action as parameters and returns a new state based on that. This function also should be pure.

What is a store?

A store is the centralized place for Redux to manage state.

What is an action creator?

An action creator is a function that returns an action.

What is an action?

An action is an object with a key of type or it is a function that can dispatch like in the case with redux-thunk. When an action is dispatched the reducer runs with the action on the second parameter which should change state.

What are the differences between an async function and a regular function?

An async function will always return a promise whereas a regular function will not. An async function supports the use of await and a regular function does not. An async function will run asynchronously whereas a regular function will run synchronously.

What is an uncontrolled component?

An uncontrolled component is one where react it not aware of the state change. It is very uncommon to need to use an uncontrolled component, but it can happen in the event of 3rd party libraries and inputs for uploading files.

What is a stateless functional component?

Another way to create components without using ES2015 classes.

What is event delegation? Why would you use it?

Event delegation is allowing an element to be the delegate for an action. For example, if you have many "li" elements inside an "ol" element and you want an action for each "li" then you can assign an event listener just to the "ol" which will be the delegate for all the "li" elements. This allows for one event listener instead of many.

What does idempotent mean? Which HTTP verbs are idempotent?

Idempotent means that the side effects will be the same for one or more of the same requests. The idea is that the state changes just once no matter how many times a request is made. GET, PTACH, and DELETE verbs are all idempotent.

What is a resource?

If it similar to an object in an OOP language. A resource is an object with a type, associated data, and a relationship to other resources. The standard methods on the resource are the HTTP verbs.

How does data flow in a React application?

If think about our react application as a tree with the main component at the top comprised of smaller and smaller components data flows down through the tree passed as props.

How does data flow in a React/Redux application?

In general components should be connected to Redux when they need to be connected to Redux. For example with react only data will always flow up and down with no side movement allowed. When Redux is connected it allows sibling components to access state without flowing up and down so with Redux the application may have less flow up and down but the data does flow in a similar way.

What is redux-thunk and why would you use it?

It allows actions to be function instead of just objects with a key of type. It is middleware that allows actions to be dispatched whenever you would like them to be instead of immediately. It also allows multiple actions to be dispatched.

What is the purpose of the `key` prop when rendering a list of components?

It allows react to very quickly identify which components are changed so that it knows which ones to re-render very quickly. Without this performance could take a hit since react would not be able to identify quickly which component is changed.

What is Babel?

It is a a transpiler that can covert JSX which cannot be read by the browser into JS which can.

What is Webpack?

It is a utility that can package up all CSS/images/JS into a single file for the browser which helps reduce the number of HTTP requests to help with performance. It also has hot reloading which can help with performance.

What is a single page application?

It is an app that re-renders content on the page based on navigation and not getting new html from a server that refreshed the page.

What is the component life cycle?

It is the stages that a component goes through. A component will mount, update, and unmount throughout its "life". Lifecycle methods are provided to tap into these stages of the lifecycle and perform actions at certain times.

What is the purpose of the React Router?

It is to do client-side routing. It is to trick a user into thinking there is new html being sent from a server and that they are actually changing html pages. In reality, client side routing will send one html file but will load different component based on the url.

What is JSX?

It is very much like writing HTML in JS although it isn't valid HTML or JS. It allows us to write React components very easily and then it is converted with Babel for the browser.

What is JSON?

JSON is a string that looks like a JS object. It is a common data exchange format for sending data between servers and clients. Since everything in HTTP is sent as strings, JSON allows the ability to convert those strings into usable JS objects using JSON.parse and JSON.stringify to convert a JavaScript object to JSON.

What is the value of using JSONSchema for validation?

JSONSchema can allow for a more specific validation scheme than if everything was coded in JS. For example, to verify 15 inputs it would take a lot of if-else statements to get exactly the validation that you would like. This makes the code unreadable. JSONSchema will also allow for standardization. For example, even for a couple of inputs there are many different ways validation can be done.

What is a JWT?

JWT stands for a JSON Web Token. It is a way to securely transmit information over HTTP. The three parts of the JWT is the header, payload, and signature. The header contains metadata, the payload contains the actual information, and the signature. The signature is generated by signing the header and the payload with a secret key. If any part of the JWT is tampered with, the signature will become invalid.

What is middleware?

Middleware are functions that run in the middle of a request response cycle. We can use middleware to intercept the request in order to modify it so that routes can use the updated response and take advantage of it.

What is the difference between Node.js and Express.js?

Node.js is a technology that allows for JS to be run in a server-side environment. Express.js is a framework for building web applications using Node.js

What are some limitations of AJAX request?

One limitation is that the calls are asynchronous. If you need specific data from a call in order to accomplish something else you will need to be mindful about how you manage async code. This can lead to confusing code if not done correctly. You could potentially have different parts of the page load at different times because of this which could confuse the end user. Another limitation is security. With AJAX, you can't make HTTP requests to all APIs due to security problems (see below answer).

What are two different ways to handle page-not-found user experiences using React Router?

One way could be redirection to a page that does exist. Another could be to display a message on the screen saying that this page is not found by perhaps having a general `ErrorHandler` component.

What are some ways of managing asynchronous code in JavaScript?

One way we can manage asynchronous code is through promises. In this way we can avoid many nested callbacks. When an asynchronous function returns a promise then we can use a .then and .catch to state what should happen after the promise is resolved or rejected. If there are multiple async functions that need to run after each other then .then can be chained to avoid nested callbacks. Another possibility is using async await with try catch. If a function is declared as async and there are async functions within that function then we can await the response from the inner function. The await will extract the value form the resolved promise. The reason we use catch is that if the promise is rejected then it can be caught.

What are propTypes?

PropTypes provide light validation on the types of props in your components. If a prop is not of the same type specified in propTypes a warning will be raised.

What is the difference between Component and PureComponent?

PureComponent implements a shouldComponentUpdate, which will do a shallow comparison and will only render if the new state and/or props are different.

What are important differences between Python and JavaScript?

Python allows for comparison of dictionaries and lists whereas Javascript doesn't. For example, [1,2,3] !== [1,2,3] in JS however in python [1,2,3] == [1,2,3]. Python has an out of the box data structure called a tuple which is not natively out of the box for JS. Python and Javascript also have very different syntax. Another difference is that Python has out of the box testing with doctests unlike JS which requires writing tests in another file. Python throws more errors than JS whereas JS will return undefined instead of throwing an error. This can make it difficult to debug JS but also allows someone to take advantage of the idea that JS doesn't throw errors.

What are some differences between client side and server side routing?

React Router has a component called `Redirect`. Since this is not server side redirection there isn't another GET request being made but instead just re-rendering content based on where the `to` prop is set to. Another way to redirect is through `this.props.history.push`. This method will add to the stack the list of routes the user has gone to instead of replacing the last time like the `Redirect` component does.

What is React? When and why would you use it?

React is a front end framework that allows us to build front end applications. React has reusable components that know how to render themselves and can be reused. This can make it easy to build applications that take advantage of this. React also has re-rendering when state changes which can make it easy to make single page applications.

What is Redux? Why would you use it?

Redux is the idea of having shared state so that any part of your application can access and change state if setup to do so. You would use Redux whenever you need shared state. In the context of React you would use Redux when you have an application where state is kept up highly purely for the reason that a component needs it. For example, if you have a component hierarchy which is 5 levels deep and only the bottom left component and the bottom right component need state then you would have to maintain state all the way at level 1 and pass it down as well as pass down functions to change state to level 5. Redux would eliminate that problem. Redux is used when there is a ton of prop drilling just for the sake of having a child component have access to state. It also keeps components clearer in their purpose.

What is a React `ref` and when might you use them?

Refs are a nice way to tap into direct DOM manipulation for certain actions like focusing.

What are some difference between state and props?

State is mutable whereas props are not. When state is changed a component is re-rendered. Another difference is that state is not passed down to child components. The only way to pass information down to children is through props.

What is the difference between a static method and an instance method?

Static methods are called directly on the class, whereas instance methods are called on the instance. You create static methods to either make special instances or when you need behavior that needs to exist before an instance is made (trying to see if something is an array using Array.isArray)

Why is using an array index a poor choice for a `key` prop when rendering a list of components?

The 2 things that a key should be is stable and unique. An index would be unique but it would not be stable since the array can mutate and indices can shift around.

When might you not use jQuery?

The DOM API is more standardized than it used to be, which makes jQuery less valuable. If you are making a simple application, then it doesn't do anything that the DOM API doesn't which could create an unnecessary dependency.

What is the purpose of the `<Provider>` component?

The Provider component is brought in when redux is needed and it wraps the App component. It is needed because it takes a prop of the redux store and so this component is essesentially connecting react with redux.

What is the purpose of the `connect` function? What does it return?

The `connect` function allows a component to be connected to redux. The first parameter is a function that will map redux state to react props and the second parameter is a function that will map dispatch to props. The `connect` function will return a function that is usually immediately invoked with the Component as the parameter to connect it.

What is the keyword `this`?

The `this` keyword is a reserved keyword in JavaScript. Every (non-arrow) function gets a value for this keyword. Inside of a class, the `this` keyword will usually refer to the current instance.

What is the `event` object? What kinds of things are in it?

The event object is an object that contains information about the event triggered. One property of the event object that is useful is the event.target property on the event object which is the HTML element of the event that was triggered. You can also access the X/Y coordinates of an event and much more in the event object.

What does the `next` function do?

The next function will allow the next piece of middleware in succession to run.

What is the purpose of the rest operator?

The rest operator collects the remaining function arguments and puts them into an array inside the function body. For example, if we have: ``` function someFn(a, b, ...others) { // do stuff } ``` and we call someFn(1, 2, 3, 4, 5), then the scope of `someFn` will have a variable called `others` whose value is the array [3, 4, 5].

What happens if you forget the `await` keyword in front of an asynchronous expression?

The return value will be a promise instead of the eventual value of the async expression (we'll talk more about promises when we get to Node).

What is the signature portion of the JWT? What does it do?

The signature is the result of concatenating the header with the payload then hashing that data with a secret key. The signature portion of the JWT ensures that the token cannot be tampered with. Only the server can create tokens because only the server knows the secret key used in the hash.

What is the purpose of the spread operator?

The spread operator spreads an array into function arguments. For example, `Math.max` accepts an unlimited number of arguments. If we have an array that we want pass to this function, we can spread it out when we pass it in: `Math.max(...[4, 2, 1, 8, 5, 6])` TL;DR - rest pulls function arguments into an array, spread extracts array elements and passes them as function arguments.

How can you implement authentication with a JWT? Describe how it works at a high level.

The user sends a request to create an account or to login. If the login/creating is successful, a JWT is created on the server side using a secret key that only the server knows. The payload in the JWT contains something that will uniquely identify the user (like a user id). The client must save the token somehow. Typical ways to save the token are in local storage or as a cookie. To make an authenticated request, the client must provide the token as specified by the server. Typically the token is sent in a header called Authorization. The server will then verify the token. To verify, the server take the header and payload and tries to sign that data using the secret key. If the signature in the token matches the signature presented, then the token is verified. The server then looks inside the payload of the token to get the unique identifier for the user to figure out which user has been authenticated.

What are three features of the Redux developer tool in Chrome?

Viewing the state tree, seeing tests for reducers, skipping/jumping to other parts in state and much more!

In the Hack or Snooze API project, what did we use async/await for?

We used async/await to handle asynchronous actions, specifically AJAX requests. We used the await keyword to pause/block code until we received a response and used the async keyword so that we could use await inside of functions.

What in React makes the `render` function run?

Whenever the component is rendered for the first time or when setState is called.

If a JWT is intercepted, can the attacker see what's inside the payload?

YES! With a standard HS256 signature, the header and the payload are not encrypted. So an attacker can easily see what's inside both. The signature just ensures that that data cannot be changed. It doesn't ensure that the data is private. So do not put sensitive data inside the JWT.

What are two ways of handling redirects with React Router? When would you use each?

`Redirect` and `this.props.history.push`. Some of the differences between the two are in my answer for handling redirects. You would use `Redirect` when you wouldn't want someone to come back to the page such as unauthorized and form submission for buying an item or creating an account. You can use `this.props.history.push` when you don't mind if someone could hit back and come back to the page.

In JS: `let a = [1, 2, 3]; b = a.slice(); a.push(4);`: does `b` contain 4? Why or why not?

`b` does **not** contain 4 because it is a different address in memory. Since we used the `slice` function, `a` and `b` are not the same reference anymore.

What does the `bind` function do?

`bind` is a method on functions. It returns a new function to you, and allows you to reassign the value of the keyword `this`. For example, suppose you have a function: ``` function fn(a, b, c) { // do stuff } ``` When you call `fn.bind`, you get a new function which will be like a copy of `fn`. The first argument to bind will be the value of `this` in the returned function copy. Any subsequent arguments to `bind` will allow you to preset arguments: for instance, `fn.bind({}, 1)` will return a function with the same body as `fn`, but the value of the keyword this will be `{}`, and the value of `a` will be 1.

When would you use `componentDidMount`?

`componentDidMount` will run after the constructor and render runs for the component. This is typically the place to do authorization, timers, and API calls.

When would you use `componentDidUpdate`?

`componentDidUpdate` will run after render runs when a component is updated. Typically this is used to update localstorage with the most recent information, auto-saving, or updating the virtual DOM for uncontrolled components that only update the actual DOM.

What is the purpose of `componentWillUnmount`?

`componentWillUnmount` is the last method that will run before the component is taken out of the DOM. This is the place to "clean up" (invalidating timers, canceling network requests, removing event handlers directly on the DOM, and cleaning up subscriptions).

What does the `mapDispatchToProps` function do?

`mapDispatchToProps` is a function that takes dispatch as a parameter. This function will return an object with the values of keys being functions that dipatch actions. The keys are then accessible to the component in order to dispatch certain actions. Without this function a component can still dispatch but will be able to dispatch any action. This function limits the actions that a component can dispatch which is useful because it makes the purpose of the component clearer.

What does the `mapStateToProps` function do?

`mapStateToProps` is a function that takes redux state as a parameter and returns an object. That object's keys will be accessible in react props. `mapStateToProps` also determines if the render function for a component will run. If the state changes since the last time `mapStateToProps` runs then render will run since the component is receiving new props.

What is jQuery?

jQuery is a library for manipulating the DOM, adding event listeners, animating elements, and making HTTP requests. Libraries are smaller than frameworks and therefore do not have the same amount of documentation and a set of strict ways that you should use the library unlike a framework.


Ensembles d'études connexes

HW/MIDTERM REVIEW QUESTIONS - MIDTERM #3 (11/12/16)

View Set

Interpersonal Communication Final

View Set

ANTH 2302 chapter 8 quiz questions

View Set

Ch. 7 bone Elongation, Zones of Metaphysis

View Set