# Interview Questions ## BQ ### Introduction - for the project, talk about what kind of the UI components you have done - think what day is the last day for your most recent project - can also talk your open source experience - show yourself, what applications you were built before, how you contribute your company - most recent project: tech does not make sense w/o example ### Projects ``` For every projects on the resume, need to think 1. team 2. frontend/backend language 3. where did you deploy 4. CICD ``` ### Must Ask Questions - Introduce yourself - most recent project - What's the biggest challenge in this project ### Work flow | Development process ``` 1. your team members(how many frontend/backend, designer, PM) 2. sprint process, sprint length, story point(how you estimate the time of finishing a task) 3. production release frequency 4. progress management software ``` Our team use scrum and manage the progress with Jira platform. We designed the sprint length to be 3 weeks. We have the backlog of all stories related to the project. In the sprint plan meeting, we'll see the priority of the story and divide the story into tasks, and developers can pick Jira ticket for the task, we'll estimate the story point(1 day, 3, 5, 8, 13) First, it might be a new feature or a bug that needs to be fixed. So, depend on the request, I'll have a meeting with other teammates such as backend developer or designer to have a general idea about how to do this task, we'll also put the agreement on the Jira board to make sure everyone knows about. I do this because when I was a junior developer, After the meeting, if it's a new feature, I'll create a feature branch under our dev branch to build this feature. I'll commit my code every time I finish a functionality, and write unit tests and run tests in my local environment, if all the test passed, I will push it. After I pushed my code to the repo, our CICD pipeline will automatically run testing, linting, and if all the test passed, I'll send a pull request, then other developers and tech lead will do the code review for it, if they find any issue, they can comment below and put the link on Jira board, so I'll reply or fix it. And if there're no issues anymore, we'll agree on that, the tech lead will approve to merge with the dev branch. CICD will run test, lint, built again and then deploy it to our dev server. And I'll first playground with the dev server because in my local machine, I use mock data, but on the dev server, we have real data there. And our QA team will also do manual test and E2E on the dev server, give us feedback. If it's good to go, we'll finally merge this branch into production branch. After this, our CICD will auto deploy it into production server. ### Why do you choose Highchart I didn't join the process when they decided which library to use.(`mention this! So they won't ask you about why Highchart, but you still have to know some comparision between Highchart and others`) We have an internal charting module which wrap the highchart component with React. Highchart is good, charts can be very interactive, data can be post-processed in the client and they use WebGL(a JS API to show 2D/3D graph) to boost the module so we can have a million data points rendered on the screen in a second. D3 is similar to JQuery, it's lower level library. ### How do you feel about Highchart It's great and easy to implement in React. They have build-in `HighchartReact` component with options, which allows us to customize the label information. We use the react portal to add label component onto the charts. `I'll paste a codesandbox link of example` ### cross-browser tests tool BrowserStack ### cross-browser issues We can use CanIUse(https://caniuse.com/) website to know whether a feature is supported on which browser version. Usually it's test by our QA team, they use BrowserStack, my duty is to fix those issues. * *date picker is not supported in desktop Safari* For example, in my most recent proj, because it's an internal project, we only have to meet the requirement of chrome 88 and safari 13, there's no much cross-browser issues, but one thing that we fixed was the date picker component, which is not supported for Safari. * *localStorage is not supported by incognito mode(匿名模式) on chrome* In my `project/company name` project, there're several cross browser issues because we would like to support many browsers including IE. We were using `localStorage` to store user informations like user behavior to improve user experience. For example, when the users is filling a form, but he misses clicking something which redirect to some other pages, we can still have his information in our `localStorage`, once he comes back to our website, he can continue to fill the form w/o losing his information. I took the responsibility to check if this user friendly feature works well on each browser, I do the error boundaries to test if it'll throw error, it works fine on every browser! However, there was a bug reported by the QA team that in the chrome incognito mode, it doesn't work and the app crashed because the localStorage is not supported by the chrome's incognito mode. Eventually, we decided to discard this user friendly feature.(it's okay to discard this feature because it's just for user experience improvement) ### Most recent task `❗️ Talk something small, like debugging, styling, not build something from scratch.` ### What was the most recent bug you fixed in your last project? `It's easy to talk about CSS bugs` * `!important`: (from Patrick's example) The most recent bug I fixed was related to styling using CSS. I was trying to override the color of a font awesome icon based on the requirements, but it wasn’t working. After digging into the code, I realized whoever was working on this before me used `!important` on all the font awesome icon colors. In my opinion using `!important` is a bad practice because it makes debugging really hard. So later during the daily meeting, I pointed it out to the team, and we all agreed to avoid using `important` unless we had no second option. * RWD bug: when switching from desktop into mobile. * cross browser issue ### Talk about one test you wrote ### Tell me about your scrum ### conflict `Not about who's right, who's wrong, agree with disagree` ### challenge of working remotely, how would you make yourself work efficiently `communication is more important` need to spend more time on communication part because for onsite, if we have a question for a person, we can directly talk, but with remote, we can only using message tools like slack, or email, we can also host a meeting, but if it's a small question, we won't do that. But I'm familiar with remote working, before COVID, we can have 1 day remote per week, and I found it makes me working more efficiently because I won't be bothered by other's talking, when work at home, I'll schedule my whole day, and usually I can finish all the todos on the list. When working remotely, I'll make sure I follow all the messages from my colleague because I know some messages might be urgent and I don't want to miss them. ### What would you do if you cannot meet the deadline Usually, I can meet everything on time. ### Tell me about a time you fail, how did you solve that situation ### How would you handle developmen with big team (50~200) Communication is important, when I'm going to solve some conflict with other's code, I'll host a meeting with the developer and make sure we find an agreement with how our code can be merged. # JS ### ❓ Closure A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures can be created every time a function is created, at function creation time. Reack Hooks heavily rely on JS closures, because with CommonJS, hooks are ready to use with import and export without touching the hook functions inside. That’s why hooks are so expressive and simple. ### spread operator Allows an iterable such as object, array, or string to be expanded. ### var, let, const * var: functional scope. Can do hoisting, so if you get value before assigning value, it'll be undefined. * let: block scope. ![](https://i.imgur.com/uV7dzF3.png) ### JS how to do inheritance use prototype chain ### What are scope, closure and this? Scope determines the accessibility (visibility) of variables. ### == vs === `==` will do coersion, `===` will not. For example, `123 == '123'` is true because `'123'` will be coersed into `+'123'`. ### ❓ Shallow copy and deep copy. * Shallow copy: Can use object assignment and spread operator. If one item is shallow copied from another, they share the same address, one change, another change. * Deep copy: Ways to do deep copy: 1. `JSON.stringfy` 2. Underscore and `Lodash` can help doing deep copy. ### lodash / underscore: JS utility libraries. * lodash highlight of loadash is it optimizes the performance of JS build-in methods like map, sort, etc. There're also many useful JS functions like `debounce` , `sortBy`, `map`. Most of the functions in `lodash` looks similar to ES6 features but is powerful, ex. the `map` in `lodash` can iterate on object and has better performance. * underscore average performance ### What is Async JS is single thread, so it's synchronized. But sometimes, we need to handle Asynchronous code takes statements outside of the main program flow, allowing the code after the asynchronous call to be executed immediately without waiting. ### Promise promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it’s not resolved. A promise may be in one of 3 states: fulfilled, rejected, pending. ### How did we do async tasks before promise was introduced? We use callback functions. But there is a big disadvantage to it when there are many async steps to a task. It’s known as callback hell. It makes the code very difficult to read and debug. That’s why we use promise instead, because we can simply chain the steps by using .then. ### super invoke constructor function ### event loop JS is single threaded and just one thing happens at a time. With the help of event loop we are able to run the async code. The event loop continuously checks the call stack, which is LIFO (last in first out), to see if there’s any function that needs to be run. While doing so, the event loop will add any function calls it finds to the call stack, execution of these is done in order. When async function like setTimeout() is called, the browsers starts the timer. Once the timer ends, the callback function is put in the message queue. The message queue is where all the user-initiated events like click or keyboard events are queued before the code reacts to them. The event loop prioritizes the call stack and completes all the processes in it first and then moves to the message queue. Every time an async function is called, a separate thread is created for them in the browser. ### debounce / throtte debounce: invoke a function after a certain amount of time. Ex. execute this function only if 100 milliseconds have passed without it being called. Syntax: `_.debounce(func, time)` throtte throttle: A throttled function is called once per N amount of time. Any additional function calls within the specified time interval are ignored. Ex. execute this function at most once every 100 milliseconds. This can be use to avoid overworking. ### bind/call/apply bind vs call/apply: bind will not invoke the function but call/apply will call/apply: argument for call is parameter but apply using array of parameters ### Destructuring making it possible to unpack values from arrays, or properties from objects, into distinct variables. ### map vs foreach `map` returns a new array without changing the original array. `foreach` doesn’t return anything so it returns undefined. # React/Redux/Hook ### Virtual DOM - It’s a representation and a copy of UI that is kept in memory and synced with the real DOM by a library such as ReactDOM. When re-renders a component, ReactDOM library is using a Diff algorithm to compare the difference between previous virtual DOM and current generated virtual DOM and figure out a bet way to update the real DOM efficiently. ### Class components vs functional components There are two types of components in react: class components and function components. Before react came up with hooks, class components where the only components which maintained the state and functional components only did the ui representation. In order to reuse a lifecycle logic, we had to wrap a component into another component. These are known as **HOC**(high order components). When we used many HOC’s in our project it would lead to HOC hell like the callback hell. In order to avoid this, react came up with hooks, now even functional components are able to maintain the state by using the custom hooks, which also make the code much cleaner. ### Server-side-pagination vs client-side-pagination - Server-side-pagination is usually done by the client providing a key that is passed to the server and then the server only selects out that “page” of data. For example if you were displaying people by last name, the first page might be created by telling the server that you want people with the last name of ‘A’ and that you want 10 rows of returned. - Client-side-pagination, the server sends all available records to the client, and using JavaScript, these results are split into pages and rendered client-side. - Client-side-pagination, changing pages or item ordering has a quicker response due to minimizing API calls to server and enhances user-experience. ### JSX A syntax sugar, looks like JS+HTML, need compiler(ex. babel) to transpile it into JS, let the browser understand it. ### What is in the header of JSX file ### super and props ### state and props ### Debug React I use Chrome dev tool, Redux DevTool ### ❓How do you handle error boundaries? Normally I would use try catch block to catch the error. And also there are other ways to trace the error such as componentDidCatch and Axios interceptor. ### Talk about the life cycle method in React. There are three phases: `mounting`, `updating` and `unmounting`. We have constructor to initiate the states and variables. Then go to render method. - Mounting `componentWillMount` is executed before rendering, on both the server and the client side. `componentDidMount` is executed after the first render only on the client side. **This is where AJAX requests and DOM or state updates should occur.** This method is **also used for integration with other JavaScript frameworks and any functions with delayed execution** such as setTimeout or setInterval. We are using it to update the state so we can trigger other lifecycle methods. `componentWillReceiveProps` is invoked as soon as the props are updated before another render is called. We triggered it from `setNewNumber` when we updated the state. - Updating `shouldComponentUpdate` should return true or false value. This will determine if the component will be updated or not. It's default value is true. If you are sure that the component doesn't need to render after state or props are updated, you can return false value. `componentDidUpdate` is called just after updating. - Unmounting `componentWillUnmount` is called after the component is unmounted from the dom. We are unmounting our component in main.js. ### ❓What is the use case of `getDerivedStateFromProps`? `getDerivedStateFromProps` is a *static* method which is invoked after a component is instantiated as well as when it receives new props. Since it is a static method, you cannot access this inside this method neither you can access any other class method. Most of the time we don’t need it. ### HOC vs render props Both of them are a React pattern which helps us to reuse life cycle method logic. - HOC is a **function** that takes in a component then returns a new component. - Render prop is a **function prop** that a component uses to know what to render. render prop is easier to set up with less boiler code, it could **easily have too much nesting** similar to callback hell ### prevent re-render 1. Use pure component 2. `useMemo` ### Data flow in React Normally in React app using one-way data flow, passed from top to down, which is parent to child. But actually. it can work as two-way data flow, child component can use callback functions to update the parent component ### Pure Components It is similar to React.Component. The difference is that React.Component does not implement shouldComponentUpdate(), but React.PureComponent implements a shallow prop and state comparison. ### What is the benefit of using pure components Pure Components would do the shallow comparison of previous state and props to avoid the unnecessary re-render. It is a good approach to do the optimization for the react app. It is a performance booster since only the things that need to be re-rendered are re-rendered. ### React Fiber React Fiber is an ongoing reimplementation of React's core algorithm. It is the culmination of over two years of research by the React team. The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames. Other key features include the ability to pause, abort, or reuse work as new updates come in; the ability to assign priority to different types of updates; and new concurrency primitives. ### The difference between React and Angular Angular: framework (only need CRA to create Angular apps). Must use TypeScript in Angular. A lot of built-in APIs and using built in testing framework. Module base. Interacts with the real DOM. Two-way data flow, OOP. React: library (need to find a boilerplate and other libraries). Can use Vanilla JS or TypeScript. Virtual DOM. Components based. One-way data flow. functional programming. Can use any testing tools like Jest. ### What are fragments in react? In react, components usually return multiple elements. Fragments lets you group a list of children without adding extra nodes to the dom. You can define them by <React.Fragment>…</React.Fragment> or simply use empty tags < ></ > ### How did you improve the performance of your application Use Chrome dev tool performance category to check if there's any memory leak, if not, try - React Lazy loading Situation: Since we bundle all the code components and put them in JS chunk which is later sent to the browser. As the number of components increase, the size of the bundle also increases. This can make the application slow. Sol: to overcome this, react came up with a function to **lazily load the react components through code splitting**. Lazy loading is the technique of rendering *only needed or critical user interface items first*, then quietly *unrolling the non-critical items later*. With Code splitting, the bundle can be split to smaller chunks where the most important chunk can be loaded first and then every other secondary one lazily loaded. - `useMemo`: to avoid keeping redoing complicated calculation, it will cache the result of calculation, and only if the dependency array changes, it'll redo the calculation. - `PureComponent` with `useCallback`: `useCallback` can used to memorize a function instance, no often used ## Redux It is a global state management tool which follows Flux structure. It contains store, reducer, action, dispatch(change state inside store). For example, in my most recent project, we use Redux to ### Did you use Redux in your project? What was the purpose? - make sure all app behave consistently. We use Redux to store everything like client's location, age, claims, and when their information changes, the data visualization component will know, and call backend api to do some big data calculation and return results to show on the charts. - easy to test: we use Jest to test Redux, for example, we test when a claim action was made, will the claim be added onto the claim state. - purpose We migrate our all states from class components into Redux because we want all the applications behave consistently, so if anything changes, other application will change, and when some data goes wrong, we have to do the debugging, and we can just go to the Redux store to see all the reducers instead of searching from tons of components to find where did we do the data manipulation. ### How many reducers did you have in your application Around 40 to 50. ### How did you use Redux in your project? In other words, how did you adopt Redux into your existing application. (An alternative question that this response could also answer to is: What was your biggest challenge during your last project?) 1. identified all the shared states from different components. 2. **writing reducers** from top to bottom; in other words, we started from the “most parent” component which used shared states. 3. **create a Redux store** and **wrap the main app component with redux provider**. Then inside the associated components, we use hooks such as `useSelector` and `useDispatch` to interact with Redux. 4. test if it’s working correctly. If it works, we move on to the next component; if not, we debug until it’s fixed. ### How do you connect Redux to React components? I used to use the HOF connect to wrap the component, but after react-redux released version 7.1, I started using hooks such as `useSelector` and `useDispatch`. ### Disadvantages of Redux Redux has a big boiler plate and a deep learning curve for most beginners. For example, to set up redux, we’ll need to create a store, actions, types, reducers, and in React components we need to use connect or some redux hooks to use and change the states. ### How two components communicate without using redux in react app 1. using normal way, passing data from parent to child using props, passing data from child to parent by passing a callback function to child as props 2. context api ### ❓**Redux Thunk** - Redux Thunk is a middleware that lets you call action creators that takes a dispatch function and return a new dispatch with an new action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed. ## Hooks ### What are React hooks? ### Advantages of using hooks | Disadvantage of class component 1. produce **less code** which makes the project more maintainable. 2. we can create **custom hooks to reuse component logic** instead of using HOC which could easily cause HOC hell. ### What are some factors that could affect a React app’s performance? And how would you solve these performance issues? There are two main factors that could affect a React app’s performance. 1. **unnecessary re-renders** from components that have expensive computations. To solve this issue, we could use `useMemo` or `useCallback` to memorize functions. For example, there was a performance issue about our data visualization dashboard, 2. memory leak: **forgetting to clean up** subscriptions/event listeners/intervals etc. in componentWillUnmount/useEffect. To solve this issue, we could simply clean it up in componentWillUnmount/useEffect. ### What is `useState` store state in a functional component. It returns a pair the current state value and a function that lets you update it. [state, setState] ### What is `useMemo` useMemo is used for performance optimization, specifically, it memorizes the output of a function and  accepts two arguments: a function and a list of dependencies. useMemo will call the function and return its return value. Then, every time you call useMemo again, it will first check if any dependencies have changed. If not, it will return the cached return value, not calling the function. If they have changed, useMemo will call the provided function again and repeat the process. ### What is `useRef` The purpose of useRef is that it allows you to persist a value across renders but unlike useState, it will not trigger a render of the component. It accepts an initial value and returns an object that has a current property. ### How do you make API calls in functional components We can use event handler but the Better practice is using `useEffect`hook to mimic `componentDidmount` lifecycle. ### How did you use `useEffect` hook in your project? We can use useEffect to mimic the lifecycle methods like `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` To mimic `componentDidMount`, we just leave the dependency array empty. to mimic `componentDidUpdate`, we add the related dependencies into the dependency array to mimic `componentWillUnmount`, we return a function which does cleaning up, such as clear interval, unsubscribe. In class component, we separate subscription methods into `componentDidMount` and `componentWillUnmount` , but use useEffect, we can put them in one useEffect. ### What is Context API? a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application. # Compiling, Transpiling - How to config Babel in your react project. ## Babel can help us to do compiling, for example, compile our JSX to JS syntax using react preset. ## Webpack webpack is a static **module bundler** for modern JavaScript applications. When webpack processes your application, it internally builds a **dependency graph** which **maps every module your project needs and generates one or more bundles**. ### Loaders in webpack - 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. For example, Babel-loader can transform files from a different language like JSX to vanilla JavaScript. - The loader array includes like Babel loader, SCSS loader, rollup.js… # Others(Performance, devOps...) ### Did you have any performance issues beforehand? Pat Example: Real-time data and there’s some memory leak stuff that slows down the performance. This problem was reported by our testing team and I Used the **Chrome dev tool** to track down the issue. The way I solved it is that I cleaned the set-Interval and every time user go from one component from another component, the subscriptions would be cleared in unmounting phase and finally our app works well. ### Solve performance issues Use chrome dev tool and the profiler(https://zh-hant.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html) in React developer tool(chrome extension) to check the performance and see what's the reason of performance issue. Depends on the issue, we have different solutions, if it's... #### first time loading slow(bundle size big) 1. ✅ React Lazy Loading: initialize objects that are critical to the user interface first and quietly render noncritical items later `React.lazy()` makes it easy to create components that are loaded using dynamic import() but rendered like regular components. This automatically causes the bundle containing the component to load when the component is rendered. https://blog.logrocket.com/lazy-loading-components-in-react-16-6-6cea535c0b52/#whatislazyloading 2. ✅ Tree shaking: A feature in Webpack to reduce the size of your bundle and improve performance, relies on ES2015 module syntax, i.e. import and export. https://webpack.js.org/guides/tree-shaking/ 3. Defer Third-Party JavaScript Script: This instructs the browser to download the script as soon as it’s found 4. Remove Unused CSS #### data too large 1. ✅ React-window(old version: React virtualize, https://github.com/bvaughn/react-window) 2. ✅ infinite scroll 3. ✅ server side pagination #### unnecessary re-render 1. ✅ useMemo 2. ✅ PureComponent The difference between PureComponent and Component is that Component does not implement shouldComponentUpdate(), but PureComponent implements a shallow prop and state comparison. 3. ✅ Redux Reselector #### images load slow 1. Lazy loading: lazy loading allows us to only load the images which are visible and asynchronously load the rest on-demand as the user scrolls. This reduces the number of requests on load and can speed up the process considerably 2. Responsive images: appropriately sizing large images for the device they’re viewed on ### Git workflow Create our own feature branches. Implement everything under a branch. After it’s done, merge it to the master branch. There might be some conflicts we need to handle before merging. Make a pull request for merging and other people will do the peer review. If there’s some problem, we make some comments on the pull request. Plus, we followed **solid principles**. Follow the company rules and make sure you write good and reusable code. ### SOLID Principles of Object Oriented Design - S(Single-responsibility Principle.): A class should have one and only one reason to change, meaning that a class should have only one job. ### CICD process After you push your code on to the pipeline, the CICD pipeline will automatically triggered testing, linting, building to see if it's good to go ### What is CI/CD CICD is listening the change that's made by our git, it's based on a YAML file, the YAML file will tell the CICD what kind of scripts you're going to run based on different branch. - CI is continuous integration, the practice of merging in small code changes frequently, rather than merging in a large change at the end of a development cycle. Establishing a consistent and automated way to build, package and test applications. It is automated all the way to push into production. - CD is continuous delivery, the automated deployment. The ability to deploy often using automation. Ensure that software can be released reliably often. - For Continuous integration and Delivery pipeline, its DevOps team’s work. I can talk about how we implement that in our project. We use Travis CI/CD tool to automate 3 processes, testing, building and deploying. We setup Docker file for image generation YML file for writing and executing specific commands. Every time we push code to the GitHub repository, Travis is listening to any changes on this repository, automatically executing the YML file, auto testing, building, generating a new image and deploy the newest image to Docker Hub. The product can then be easily delivered and run right out of box. ## Backend ### Give me some example about the RESTful API you’ve done (What kind of API endpoint have you done? What kind of data? (year, model, image, etc...) Basically, in my project, as a front-end developer I was responsible for consuming APIs provided by the backend developer along with http methods such as GET, POST. In my project I used to fetch data like vehicle information in JSON format and there is some information like its model, year, name…… ### If you have many api calls associated with routes requiring authentication, what is your strategy for setting the authorization request header? I actually encountered this problem during my last project. The way we solved it was by using axois interceptors which allowed us to inject the JWT to the authorization request header before each request. ### What is Thread pool ## Web/HTTP ### What is web 2.0 and AJAX? - web 2.0 introduced AJAX technology that is a major breakthrough. Moving from a traditional Multi Page Application to Single Page Application that implements Ajax to re-render webpage dynamically. With that being said, it enables a much smoother user experience with Url navigations and reduces server-side workload ### What is a cookie? - A cookie is just a string that contains some data which is stored on your browser. **It will be sent with http request**. It can be stored in the frontend, but can be changed in the server side by using `set-cookie` header. In this way, cookie can do communication between client and server. - Cookie is also domain specific. One website’s cookies cannot be accessed by other websites. - There are usually three main use cases for cookies. Before HTML5, we don't have localStorage, so we use cookie a lot. Ex. ****store **user authentication** token - For security, we can set the attibute `HttpOnly` in the `set-cookie` , so that it **can only be access using HTTP**, and if there's some client-side script try to read the cookie, it'll be empty string. This helps to prevent cross-site scripting (**XSS**) attacks. localStorage is vulnerable to XSS attacks, less secure than cookie. ### Cookies vs local storage vs session storage - Cookie Long string, inside this string it's key-value pairs. Size is only 4KB. **Anything you save in the cookie is sent to the server with the request header by default.** - Local Storage: Map with key-value pairs. You can use JS to set some logic to inject the data to the http request body or header. More controllable. 5MB size is much bigger than cookies. Information in local storage can be deleted manually. - Session Storage: Usually sensitive information is stored here. Once we close the browser the session is deleted. ### What is axios vs fetch(), why use axios? Axios is a promise-based HTTP client which is written in JavaScript to perform HTTP communications. It has one powerful feature called **Interceptors**. Axios interceptors **allow you to run your code or modify the request and/or response before the request and/or response reaches their destination!!** There're two callbacks in request interceptor one with parameter config object and another one with the error object. Config is the object of AxiosRequestConfig which contains URL, base URL, headers request, body data, response type, timeout, etc. ``` // Add a request interceptor axios.interceptors.request.use( config => { const token = localStorageService.getAccessToken(); if (token) { config.headers['Authorization'] = 'Bearer ' + token; } // config.headers['Content-Type'] = 'application/json'; return config; }, error => { Promise.reject(error) }); ``` ### Can you decode the token from your client-side Yes, we can decode the string into some object to get the value. ## JWT ### Why and how do you use JWT for authentication? The reason why we chose to **use JWT over sessions** for authentication was because **using sessions requires us to store the session ids in a database**, but we didn’t want to deal with that because it could become a bottleneck and a thing to maintain. On the other hand, JWT doesn’t require a database to be involved. As far as how we used JWT for authentication, the workflow goes like this. When the user is authenticated for the first time, the server creates a JWT which contains the encrypted identity of the user, and sends it back to the client which is usually stored in the local storage. Now every time the client sends a request, the token will be attached to the authorization http request header. The server then gets the token and tries to decrypt it with the key which is inside the token. Yes, we use JWT to do the authentication in our project. We got a token from server, when we're going to send it back, we can put the token in the authentication header, we use `axios` and the interceptor to inject the token into our API call. ### If users get your JWT token, can users change the information and send it back to the server It will not. You can’t modify it. JWT is using a signature. Once we modify it, the server won’t accept it. ## NodeJS ### What frameworks did you ever use with NODE? ### What is PM2 package Process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. For example check status, logs, metrics, monitor web interface ## HTML - What is the HTML meta tag? <meta> tags always go inside the <head> element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings. - Where do you write the link and script in html and why? We write the link tag in the header, because if we write it at the end of the body, the html will use the default css and render the page. When the execution reaches the link css tag, it will re-render the whole page. In order to avoid the re-rendering we link the css in the starting itself. Coming to the scripts, they are placed at the bottom of the body. We know that html loads from top to the bottom, if we write the script in the header- if the code in js alters the html as soon as the js loads, the html elements will not be available for the dom manipulations. This might lead to error. Scripts can also be written in the header after the css link, by using the async and defer which allow parallel programing. - Html 5 vs before version The biggest difference is that Html5 has semantic html, which give semantic meaning to tags. For example, you can give tags the names header, footer, video etc, this enables accessibility to the disabled people. ### ARIA Before HTML5, there's no semantic tag, but we can use aria attributes to provide a non-semantic tag with semantic meating. Use WAVE to test accessibility. Ex. This means header without using `<header></header>` ``` <div role="heading" aria-level="1">This is a main page heading</div> ``` [https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role) ## CSS ### RWD I've used CSS media query, Bootstrap, and material UI before in my previous projects. The most recent project(at State Farm) was using desktop-first-design, because the end users mostly use desktop to access the website, so we simply use media query to do the RWD. Another previous project use mobile-first-design, because our client might use mobile to access that app and mobile-first-design can help us to think from the smallest screen which is harder to design and to the wider. In that project, I used Bootstrap to do the RWD like navigation component. ### How do you decide which approach to take? The mobile first or the desktop first? It mostly depends on the users. If most users for our application use smaller devices, then it’s better to take the mobile first approach; whereas if most users use bigger devices, then it’s better to take the desktop first approach. ## Algorithms, Concepts ### What is dynamic programing? An algorithm technique for solving an optimization problem by **breaking down it into simpler subproblems** and utilizing the fact that the overall optimal solution of the problem depends on the optimal solutions of its subproblems. ### declarative programming and imperative programming - Imperative programming is focusing on implementing OOP concepts and inheritance while declarative programming is functional programming oriented. Focusing on result. - For example, in react, we can build web interfaces without event touching the DOM directly. We can have virtual DOM copies without having to interact with the real DOM. React doesn’t mutate the component and we use the map() that does not mutate the original array and returns a new array. ## Angular - In angular how two components communicate? - What is rxjs