Skip to content

These are the questions from the many interviews that I appeared for the frontend role.

Notifications You must be signed in to change notification settings

HebleV/frontend-interviews-encyclo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 

Repository files navigation

frontend-interviews-encyclo

Following are the list of interview questions on HTML5, CSS3, JS, ES6, ReactJS, Redux.

HTML

1. Why do we use data tags in HTML?

The tag is used to add a machine-readable translation of a given content. This element provides both a machine-readable value for data processors, and a human readable value for rendering in a browser

2. What are the new features in HTML?

Details Tag

3. What is a DOCTYPE in HTML ?

This shows the HTML5 version

4. What are the new tags in html ?

Details tag

CSS

1. Create a google calendar

Implement using CSS grid and DOM manipulation

2. What is difference between position fixed and absolute ?

Fixed means, the position of an element is fixed wrt the window like fixed header and absolute is element is independent of window and can be placed anywhere by using top, bottom, left, and right values

3. What is difference between position fixed and absolute ?

Fixed means, the position of an element is fixed wrt the window like fixed header and absolute is element is independent of window and can be placed anywhere by using top, bottom, left, and right values

4. What is position sticky ?

It behaves like relative position until it hits a certain offset value after which it behaves like position fixed.

5. What is CSS selector specificity ?

If there are two or more conflicting CSS rules that point to the same element, the browser follows some rules to determine which one is most specific and therefore wins out. The priority order of specificity is inline style, id, classes/attributes/pseudo classes, elements/pseudo elements

6. What is flex basis ?

Its the initial size or the width of the flex item

7. What is rem and em value in CSS ?

rem(Root em) - Relative to font-size of the root element em - Relative to the font-size of the element (2em means 2 times the size of the current font)

8. What is box model ?

More Details

9. What is :is() and :where() in CSS ?

is() pseudoclass is to reduce the repetition in selectors lists. :where() pseudoclass is to keep the specificity of selector low More Details

10. How do you achieve grid and flex layout using plain CSS ?

Updating...

11. How do you remove the default gap between images that is formed when more than one images are displayed adjacent to each other ?

give the container of the img tags font-size:0px;

Check here
12. Implement a toggle button using html,css and JS.

Updating...

JS & ES6

1. Write a polyfill for bind()

Polyfill for bind

2. In a promise chain of 5 promises, what if promise 4 fails will next promise be executed ?

No, it does not execute next

3. Write a polyfill for Promise

Implement using setTimeout

4. What is the difference between Promise.race() and Promise.all()?

This returns a promise as soon as any one of the Promise is resolved where as in Promise.all(), it waits until all the promises are resolved.

5. What is wrong in below code?

```this.setState((prevState, props) => { return { streak: prevState.streak + props.count } }) ```
Answer: Nothing is wrong with it. It’s rarely used and not well known, but you can also pass a function to setState that receives the previous state and props and returns a new state, just as we’re doing above. And not only is nothing wrong with it, but it’s also actively recommended if you’re setting state based on the previous state.

6. What will be the output here in func()?

```const test = { comp: ’IT World', role: 'dev', func: () => { return `In ${this.comp}, I am a ${this.role}` } } ```
Answer:this.comp and this.role will be undefined.
But if you change above code from arrow function to normal function i.e. ```const test = { comp: 'IT World', role: 'dev', func: function() { return `In ${this.comp} i am a ${this.role} .` } }```
Answer:this.comp and this.role will be IT World and dev respectively.

7. How do we achieve inheritance before ES6 ?

Update...

8. How do we make sure that certain property only not to be updated in an object ?

Using object.preventExtensions();

9. Javascript is synchronous or asynchronous ?

Synchronous and single threadedGood read

10. What are the new features in ES6, 7,8… ?

New features

11. What would console print ?

```console.log(a); Var a = 7;```

Answer: Undefined coz Values are hoisted only when declared not when initialized. But if it is let or const then it will be ReferenceError.
12. What is the difference between a normal function and arrow function ?

More details

13. What is the purpose of call and apply ?

Answer: If you know how many arguments you would be passing then use call and if you are not sure how many arguments you would be passing or if the arguments are already an array or an object then use apply.

14. What is 5 > 4 > 3 ?

Answer:False coz JS coerces 5>4 first which is true (1) then true(1) > 3 = false;

15. What is 3 + true ?

Answer:4 coz JS coerces true to 1 and 3 + false would be 3.

16. Different ways to create object in javascript ?

Updating...

17. Find the longest subarray having sum equal to s ?

Answer:Solution

18. Merge the keys and values to form an object?

Answer:Solution

15. What is 3 + true ?

Answer:4 coz JS coerces true to 1 and 3 + false would be 3.

16. What is functional chaining ?

Answer:Updating...

17. How do you create inheritance in JS ?

Answer:Updating...

18. What is the purpose of deep cloning ?

Answer:To create a deep copy or new object independent from old one. One way is first json.stringify the object or array and json parse it. Another way is, It is created using lodash. Object.assign creates a shallow copy means the new object will still have same old references - More info

19. What are static methods ?

Answer:Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances. Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.

20. What is a singleton ?

Answer:It is an object which can be instantiated only once. So even if you repeatedly call its constructor same instance is returned

More info
21. What is the difference between map, filter, and reduce ?

Answer:Updating...

22. What sort method will you use for building web app ?

Answer:Updating...

23. How will you make sure your app is not crashed if there are no values or null in nested json objects ?

Answer:We can make use of new JS feature of optional chaining operator `?.`

More info
24. How will you find the type of an element or object ?

Answer:Using typeof

25. What is {} + [] = ?

Answer:0 because of the type of conversion which is empty object and empty array.

26. What are the type of object and array ?

Answer:typeof object = object;
typeof array = object;

27. What is the difference between slice and splice ?

Answer:Slice doesn’t change existing array but splice does.

28. What are higher order functions or components ?

Answer:The functions that can take other functions as inputs or provide functions as its output. Ex : map, filter, reduce

29. What are the differences between local, session storages and cookies ?

Answer: local session cookies Capacity 10 mb 5mb 4kb Expiry Never on tab close manually set Storage location browser browser browser n server

          Methods
	localStorage
      localStorage.setItem(‘name’, john);
      localStorage.getItem(‘name’);
      localStorage.removeItem(‘name’);
     Similar methods for session storage.

Cookies
     Document.cookie = ‘name=john; expires =’ + new Date(9999, 0 ,1).toUTCString();

30. What is the output ?

Question:a(); b(); c(); function a() { console.log(1) }

var b = function() { console.log(2); }

var c = () => { console.log(3); }

Answer: 1
Error : b is not a function

        Note: It will not even go to c() call coz of error at b(); but c() will also throw same error.</p>
31. Write a program for function sum(1)(2)(3) which gives output as 6 ?

Answer:let sum = function(a) { return function(b) { return function(c) { return a + b + c; } } }

32. What are generators and how will you know if it is an iterator ?

Answer:You can know if it is an iterator if function is preceded by * symbol.

33. What are the differences between arrow function and normal function ?

More info

34. How do you achieve inheritance ?

Answer:Updating...

35. What is function currying ?

More info

36. What are map and weakmap ?

Map doesn’t allow to garbage collect the object reference and WeakMap does allow. Map accepts objects, strings, num etc but WeakMap accepts only objects as keys. Map has size property but WeakMap does not have.

37. What is “2” + “2” - “2” ?

Answer:20 - Because + will concatenate which will give 22 and - will type coerce and convert it into numbers. So 22 - 2 = 20

38. What is typeof null ?

Answer:Object

39. What is the output console.log(a,b) { let a = 10; var b = 20 console.log(a,b) } console.log(a,b)

Answer:Reference Error : a is not defined.

40. What is the value of following ?

Answer: 0 === false; // false
0 == false // true

41. What are generators ?

Answer:Generators are basically the functions which returns the generator object which holds the entire generator iterable that can be iterated using the next() method. I has yield key word which is like return keyword. next() method will return an object with “done” flag and “value” key.

42. Why does const allow change in values when assigned to an object ?

Because it refers to a memory address not the actual object itself.

43. What are primitive data types and reference data types ?

Primitive : Number, Boolean, String, Undefined, Null Reference : Functions, Array and objects (though typeof of all are object only) For primitive, Can assign a value directly. For reference, you cannot coz you assign to an address in a memory not actual value.More info

44. What is the difference between object.preventExtensions, seal and freeze methods ?

These deals with adding, deleting, and modification of properties. preventExtensions => Doesn’t allow addition of new properties. Seal => Doesn’t allow addition of new properties and deletion of existing properties. Freeze => Doesn’t allow addition, deletion and modification of object properties.

45. What is the output for below destructuring assignment ?

1- const foo = ['one', 'two', 'three']; const [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three"

2- When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain. let obj = {self: '123'}; obj.__proto__.prot = '456'; const {self, prot} = obj; // self "123" // prot "456"(Access to the prototype chain)

More info
46. Convert the nested array into single dimension array ?

Input : let arr = [1,[2,3,[4,5,[6,7]]]]; Output: arr=[1,2,3,4,5,6,7]

47. What are rest and spread operators ?

Updating...

48. Reverse a string and print it

Check here

49. How does generators work in backend or make it iterable ?

Updating...

50. What is the difference between null and undefined ? Read here
51. How to ensure that only one of the object properties is not writable or readable ?

This is achieved using Object.defineProperty. Let name = { firstname: “john” } Object.defineProperty(name, ‘lastName’,{ value : “doe”, writable:false } ) Now you can update firstname but not lastname.

52. What would be the output in below code ? Read here
53. What is the output ?

Let x = function(){ return { message:’hi’ } } x();

Answer: x is undefined coz in a function after return statement there must be braces rather than on next line else JS will insert a comma and return.

54. What is the value of console.log(Math.max()) ?

infinity coz that is the lowest number in maths when no input is given.

55.What is the output ?

const array = [1, 2, 3, 4, 5]; console.log("a") array.forEach((el, i) => { console.log(el); });

Answer: console.log("b") // a 1 2 3 4 5 b Because forEach is synchronous even though it takes a callback function.

56.What is the output [...[...'...']].length ?

Answer: 3

57. What is the output?

let i; for (i = 0; i < 3; i++) { const log = () => { console.log(i); } setTimeout(log, 100); }

Answer: 3 3 3

58.Write a polyfill for map function ?

Updating...

59.What is the output ?

console.log(typeof typeof number);

typeof number => string

60.What are the output ?

console.log('start');

setTimeout(function () { console.log('set timeout'); }, 0);

Promise.resolve() .then(function () { console.log('promise 1'); }) .then(function () { console.log('promise 2'); });

console.log('end');

Answer: start end promise 1 promise 2 set timeout Because, promises are resolved then and there and also, the setTimeout is put into the call stack queue.

61.What will be the output for below code ?

function args(){ return arguments; }

Answer: [ ] - An empty array or array like object which is the arguments array that is automatically created while creating a function.

62.What is the value for if(0.1+0.2 == 0.3) ?

Updating...

63.Write code which handles all the below case ?

sum(2,3) sum(2)(3) sum(2)(3)(4)

Updating...

ReactJS

1. Explain the lifecycle methods of React

This can be little tricky as there are different answers for a class and a functional component. Perhaps, a better reply would be to ask if they are looking for a class component or a functional component. I believe certainly functional as it is the latest and most used. But it helps to know both the lifecycle methods.
Functional components
Class Components
Note: There is also an older version of lifecycle methods for the class components where certain lifecycle methods have become deprecated like ComponentWillMount and ComponentWillUpdate.

2. How can you handle error boundary ?

React Error Boundary

3. Why React recommends to use keys in map ?

Because React internally keeps track of items if it has changed.
More details

4. What is the disadvantage of using index for keys in map in React?

Because React cannot differentiate if the element was removed or just content is changed. So it will just compare every other DOM element.Good read

5. How do you display a default 404 error page in react JS ?

Using the Redirect method from react-router-dom
``````

6. What are the new features added in React 16.7 ?

React Hooks, React.memo, React.lazy, React.suspense, Context, error boundary, and React.Fragment.

7. What is useCallback

If there is a function(lambda function) which is re-rendered everytime then we can use useCallback to prevent it. More

8. What is virtual DOM?

Updating...

9. What is shadow DOM?

Shadow DOM API helps in encapsulation of certain hidden elements from the actual DOM nodes/elements so that the hidden code doesn’t clash with actual DOM code. Shadow DOM api provides a way to attach a separate hidden DOM to an element (Shadow Host) of the actual DOM. Example: HTML

10. How can you improve performance of React app ?

Updating...

11. What is getDerivedStateFromError() in ErrorBoundary component ?

It is used to render a fallback UI after an error is thrown.

12. What is componentDidCatch() in ErrorBoundary component ?

It is used to log error information.

13. What is React Context ?

It provides a way to pass data through the component tree without having to pass props down manually at every level. For ex: we have a parent component with some data. And it has child and grand child components. In the current scenario if we want to pass data then we will have to pass data to child then grandchild. Even though child doesn’t need data but still we are passing data. So using context we can now directly pass data from parent to grand child. It uses React.Provider which provides data and React.Consumer which accesses/consumes data.

14.How can we access DOM in React ? Can we access ?

Using Refs which are created by React.creatRef(). These Refs are created and attached to React elements via the ref attribute.

15. What is one way and two way bindings ?

one way data binding -> model is the single source of truth . whatever happens on UI triggers a message to model to update a part of data. So data flows in single direction and which becomes easy to understand. two way data binding -> any change in UI field updates the model and any change in model updates the UI field.

16. How do you render React on server side ?

Updating...

17. What is getDerviedStateFromProps in React lifecycle ?

This is the place where the state object is set based on initial props. This method can be invoked in both mounting and updating phases.

18. What is reconciliation in React ?

The process of finding the minimum number of changes that must be made in order to make virtual DOM and actual DOM tree identical. So keys play an important role in reconciliation. More info

19. Is setState an asynchronous or synchronous ?

Asynchronous - Because it makes a call to callback function More info

20. What happens if we declare setState inside render () ?

It will be an infinite loop

21. What is the difference between componentWillReceiveProps and componentDidUpdate?

componentWillReceiveProps gets called before the rendering begins. It compares incoming props to current props and decide what to render.


componentDidUpdate gets called after any rendered HTML has finished loading. It receives 2 arguments prevProps & prevState.

22. How will you declare setTimeout in React component ?

It can be declared in useEffect and then return the clearTimeout() to unmount the component.

23. What is the purpose of super in constructor ?

To bind this to parent class component

24. What is the advantage of using arrow functions in React components ?

It will bind this to surrounding code context or to function so this will avoid bugs.

25. What is code splitting ?

It is splitting your code in such a way that, only that part of code is loaded required for the current screen. You can achieve this using dynamic imports (webpack) and lazy loading react components. ( Webpack will asynchronously load the components or spits out different files for different components. ) For 3rd party libraries or vendor files, it will load for first time and cached for ever in browser, so that it doesn’t load again when user visits for second time.

More info
26. How do you measure performance of React components or application ?

1.Use React profiler to see what components are taking lot of time to load
2. Use perf library.
3. Use useMemo/React.Memo hooks to cache a component

27. What is memoization ?

Memoization is the idea of caching a value so that you don’t have to compute every single time.

28. What does useMemo/React.Memo do ?

If you are sure that a function always returns the same computed value for a given input then there is no need to recompute or recalculate the value every single time. The value can be cached. This is done using useMemo or React.Memo.

29. What are the disadvantages of using useMemo ?

One has to use useMemo judiciously and efficiently because if you use useMemo for functions which are not required to be memoized then it uses a lot of memory overhead and causes performance issues again.

30. What is useRef ?

It is like useState but it doesn’t render every time there is an update. It holds the data or persists data/update between different renders without re-rendering the component.

31. Write a 2 line code to increment count by 5 using useState ?

const [count, setCount] = useState(0); setCount(count + 5);

32. What are the advantages of using functional components over class components in React ?

  • You don't have to manually bind "this" like in class component
  • Simple and easy to test

33. How can you compare previous state and previous props in react hooks ?

By writing a custom hook using the useRef More info

34. How do you manage state now in React using hooks ?

It is like useState but it doesn’t render every time there is an update. It holds the data or persists data/update between different renders without re-rendering the component.

35. What are performance metrics that you will check for a web app ?

  • Loading Time
  • Network Requests
  • Caching
  • Code Splitting

36. How can you ensure a component or a thing is not re-rendered in class and functional component ?

Updating...

37. What is a lambda function in React ?

Everytime the component is rendered, the function is recreated.

38. What is useRef ?
  • Stores a previous value
  • Helps in persisting the state between different renders without actually re-rendering the component. In contrast useState re-renders everytime.
39. Why don’t we make API calls in constructor or componentWillMount ?

Since, JS being asynchronous, api calls will have to go through event loop then render the component and rerender it. This will increase complexity

More info
40. How to make sure that useEffect is not called again n again ?

Pass an empty array as a second argument

41. How to display value in an uncontrolled component ?

controlled means an input value must have to be stored in a state in order to access it. Any change in UI should update state. (Check in state values in react components to understand diff). React prefers to have controlled components than uncontrolled and it is also the standard. Uncontrolled must be avoided as much as possible. Here is the example

If it is for uncontrolled then use refs instead of e.target.value

Example
42. How do you pass props from parent to child using hooks ? Example 1 Example 1
43. What is alternate for componentDidUnmount in react hooks ?

You can unmount a component by returning a function which will remove the event or which unmounts the component in useEffect hook.

44. Implement a sticky footer using React JS. After certain height, it should disappear.

Updating...

45. How many ways to pass data from parent to child component ?

Updating...

46. How do you pass params in url in react ?

Updating...

47. Solve the code Codesandbox
48. How can you improve the performance of infinite scrolling for displaying a large list ?

1. Unmount the old list and load new list

2. Store in memory

Redux

1. Explain the flow of Redux

We write an action which is dispatched when an event is triggered. This inturn calls the respective reducer which doesn't directly update the state but rather makes a copy and returns a new state and thus updating the store. This will rerender the component.
Note: Usually setState is not used or required when using redux. Based on the requirements it can be used. But mostly initial states and default props should be used. As local states are difficult to maintain

2. Does reducer update data?

Yes it does but it doesn’t directly update state object but rather return a new updated object

3. How will you update/render a table list of data using react and redux ?

write one more component only for table body which will render table body given a table data. It will loop through data and render those lists.

4. How do you update data in react-redux app ?

Based on requirement we dispatch appropriate actions which can fetch api data and call to another action with type and payload or directly we dispatch action with type and data which has been sent to reducer. Note: Usually setState is not used or required when using redux. Based on the requirements it can be used. But mostly initial states and default props should be used. As local states are difficult to maintain

5. What is a Redux-thunk ?

It acts as a middleware between actions and reducers which help in asynchronous actions. It doesn’t care if action is returning an object but only if it is returning a function. In that case, it just provides dispatch functionality as a parameter to help asynchronous functionality. So in a nutshell, thunk basically provides dispatch functionality to function for giving synchronous actions to reducers. It allows you to return a promise to help in an asynchronous process.

PWA

1. What is a service worker ?
  • Runs in the background of users browser.
  • Acts like a proxy server between app, browser and network.
  • Allows apps to continue working offline in case of loss of internet
  • Efficient caching of assets and make them available when user device is offline
  • They run on a *separate thread *from the main JavaScript code of our page, and don't have any access to the DOM structure. This introduces a different approach from traditional web programming — the API is non-blocking, and can send and receive communication between different contexts. You are able to give a Service Worker something to work on, and receive the result whenever it is ready using a Promise-based approach.
2. What is manifest.json in PWA ?

It is a json file containing info about app like title, logi link, splash screen, background n theme color etc. It makes the website installable.

3. How do you make a website installable ?
  • A web manifest with all fields
  • Website is served from a secure https connection
  • An icon to represent the app on device
  • Service worker registered to make work offline
4. How do you store data offline in PWA ?
  • Using cacheAPI which is part of service workers
  • Use indexedDB with a promise wrapper
5. Explain the service worker lifecycle ?
  • The install event is the first event a service worker gets, and it only happens once.
  • A promise passed to installEvent.waitUntil() signals the duration and success or failure of your install.
  • A service worker won't receive events like fetch and push until it successfully finishes installing and becomes "active".
  • By default, a page's fetches won't go through a service worker unless the page request itself went through a service worker. So you'll need to refresh the page to see the effects of the service worker.
  • clients.claim() can override this default, and take control of non-controlled pages.
  • Install => Wait => active => Receive fetch and push events
6. What will the service worker script file have ?
  • It will have a cache-name i.e. app name
  • URLs to cache
  • Then add 3 event listeners to install ,fetch and activate.
7. How can you convert a create-react-app into a PWA ?
  • Include the above step 6q
  • Update index.html to check if client browser supports service workers by adding another event
  • listener “load” the service worker
  • Change serviceworker.unregister to serviceworker.register()
  • Add progressive enhancement principle i.e. add some html content to display default html ...loading
  • Add splash icon and update manifest.json
  • More info
8. How will you implement Server Side Rendering or SSR?

The reactjs provides the server-side rendering using 'react-dom/server' module.This module have renderToString() method to replace HTML string into the body as a response.

  • Create a server file where you import express and provide port number
  • Read the index.html from /build folder using fs.readfile (nodejs)
  • On success, replace the HTML string i.e.
    imported app component with
    ${ReactDOMServer.renderToString()}
  • In the react index.html file, replace React.render with React.hydrate
  • Serve the static files from build folder
  • Then add changes in server folder to ignore node modules and add babel preset to compile
  • Add ssr command in package.json in react app to run
  • More info

About

These are the questions from the many interviews that I appeared for the frontend role.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published