Front End interview questions compilation

December 25, 202238 min read

Javascript
React
Webdev
Career

This article is a compilation of all the questions asked during my job hunt in product-based companies.

I followed this blog during my Interview preparation. Do check this out. All front end Interview questions asked during my recent job hunt.

Interview Process

In most of the companies I went through either 4 or 5 rounds.

First Round JavaScript,CSS advance concepts with 1 or 2 competitive problems(Leetcode easy or medium). Second Round Advance Javascript and React concepts with 1 UI assignment in React. Third Round Same as previous Round but more focused on React with a Senior Dev. Fourth Round(Only in few companies) Design Patterns in JS and React. Questions about application architecture (From Previous projects) and 1 or 2 FE application architecture design problems. Fifth Round Managerial Round with some technical questions. Mostly about previous projects.

Javascript
  1. Create Promise.allSettled() custom implementation where if all promises fail then it should reject and if any promise pass it should resolve.
const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("data")
  }, 1000)
})

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("data")
  }, 3000)
})

const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("error")
  }, 500)
})

const p4 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("data")
  }, 0)
})

const customPromiseAll = promises => {
  const result = []
  let rejected = 0
  let complete = 0

  return new Promise((resolve, reject) => {
    promises.forEach((p, i) => {
      p.then(data => {
        result[i] = data
        complete++
        if (complete === promises.length) {
          resolve(result)
        }
      }).catch(err => {
        result[i] = err
        complete++
        rejected++
        if (rejected === promises.length) {
          reject(result)
        }
        if (complete === promises.length) {
          resolve(result)
        }
      })
    })
  })
}

customPromiseAll([p1, p2, p3, p4])
  .then(data => console.log(data))
  .catch(err => console.log(err))
  1. Randomize a given array.
const arr = [0, 1, 2, 3, 4]

const randomize = arr => {
  let randomIndex = Math.floor(Math.random() * arr.length)

  for (let i = 0; i < arr.length; i++) {
    ;[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]
    randomIndex = Math.floor(Math.random() * arr.length)
  }
  return arr
}

const newArr = randomize(arr)
console.log(newArr)
  1. Write a function which takes a string class name and return an array of all the elements that contain the class in document. i.e. Basic implementation of querySelectorAll() with class.
function getAllClasses(name) {
  const el = []
  let curr = [document.body]
  while (curr.length) {
    let first = curr.shift()
    const nodes = first.children
    const arr = [...nodes]
    arr.forEach(node => {
      curr.push(node)
      if (node.className === name) {
        el.push(node)
      }
    })
  }

  return el
}

console.log(getAllClasses("abc"))
  1. Write a JSON structure of a directory like which contain files, folders with nested files folders.
{
  "name": "root",
  "type": "folder",
  "children": [
    {
      "name": "file1",
      "type": "file"
    },
    {
      "name": "folder1",
      "type": "folder",
      "children": [
        {
          "name": "file2",
          "type": "file"
        }
      ]
    }
  ]
}

Now write a function to traverse this object and print output on console with proper indentation on console.

const traverse = (data, indent, obj) => {
  obj.str += "\n" + " ".repeat(indent) + data.name
  if (data.type === "folder") {
    data.children.forEach(child => {
      traverse(child, indent + 2, obj)
    })
  }
  return obj.str
}

console.log(traverse(directoryRoot[0], 0, { str: "" }))
  1. Flatten a nested object. Object property can have a string, number, array(nested),boolean, object.
const details = {
  name: "vishal",
  telephone: 9816120038,
  skills: ["Javascript", "react", "html", "css"],
  address: {
    city: "Bilaspur",
    state: "Himachal Pradesh",
    pin: 174021,
  },
  experience: {
    current: {
      company: "PS",
      time: {
        joining: "30th May 2021",
      },
    },
    previous: {
      company: "Infosys",
      time: {
        joining: "3rd December 2018",
        leaving: "24th May 2021",
      },
    },
  },
}

const flattenObjFun = (obj, prefix, flattenObj) => {
  Object.keys(obj).forEach(key => {
    if (
      typeof obj[key] === "object" &&
      obj[key] !== null &&
      !Array.isArray(obj[key])
    ) {
      flattenObjFun(obj[key], `${prefix}_${key}`, flattenObj)
    } else {
      flattenObj[`${prefix}_${key}`] = obj[key]
    }
  })

  return flattenObj
}

const flatObj = flattenObjFun(details, "details", {})

console.log(flatObj)
//output
{
  details_name: 'vishal',
  details_telephone: 9816120038,
  details_skills: [ 'Javascript', 'react', 'html', 'css' ],
  details_address_city: 'Bilaspur',
  details_address_state: 'Himachal Pradesh',
  details_address_pin: 174021,
  details_experience_current_company: 'PS',
  details_experience_current_time_joining: '30th May 2021',
  details_experience_previous_company: 'Infosys',
  details_experience_previous_time_joining: '3rd December 2018',
  details_experience_previous_time_leaving: '24th May 2021'
}
  1. Create a static funtion LastFullfilled() to Promise object. It will take an array of promises and will resolve or reject only when last promise(Takes most time) will resolve or reject.(Return only last response).
function task(time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(time)
    }, time)
  })
}

const tasksList = [task(1000), task(5000), task(3000)]

Promise.lastFullfilled = function (promises) {
  let complete = 0
  let failed = 0
  return new Promise((resolve, reject) => {
    promises.forEach(promise => {
      promise
        .then(data => {
          complete++
          if (complete === promises.length) {
            resolve(data)
          }
        })
        .catch(err => {
          complete++
          failed++
          if (failed === promises.length) reject(err)
        })
    })
  })
}

Promise.lastFullfilled(tasksList)
  .then(results => console.log(results))
  .catch(error => console.error(error))
  1. Polyfill for call(), apply(), bind()
const obj1 = {
  a: 5,
  printA(a1, a2) {
    console.log(this.a)
    console.log(a1, a2)
  },
}

const obj2 = {
  a: 7,
}

const customCall = function (context, ...args) {
  const fun = this
  context.fnRef = fun
  context.fnRef(...args)
}
Function.prototype.customCall = customCall
obj1.printA.customCall(obj2, 1, 2)
//7
//1 2

const customApply = function (context, args = []) {
  const fun = this
  context.fnRef = fun
  context.fnRef(...args)
}
Function.prototype.customApply = customApply
obj1.printA.customApply(obj2, [3, 4])
//7
//3 4
const customBind = function (context) {
  const fun = this
  return function (...args) {
    context.fnRef = fun
    context.fnRef(...args)
  }
}
Function.prototype.customBind = customBind

const bindFn = obj1.printA.customBind(obj2)
bindFn(7, 8)
//7
//7 8
  1. Polyfill of array reduce, map, flat
function customReduce(callback, initialVal) {
  let prevValue = initialVal

  for (let i = 0; i < this.length; i++) {
    prevValue = callback(prevValue, this[i], i, this)
  }
  return prevValue
}

if (!Array.prototype.customReduce) {
  Array.prototype.customReduce = customReduce
}

const value = [1, 2, 3, 4].customReduce((acc, curr, index, arr) => {
  return acc + curr
}, 0)

console.log({ value }) // { value: 10 }

function customMap(callback) {
  const newArr = []
  for (let i = 0; i < this.length; i++) {
    newArr.push(callback(this[i], i, this))
  }
  return newArr
}

if (!Array.prototype.customMap) {
  Array.prototype.customMap = customMap
}

const newArr = [1, 2, 3, 4, 5].customMap((value, index, arr) => {
  return value * index
})

console.log(newArr) //[ 0, 2, 6, 12, 20 ]

function customFlat(arr, depth) {
  return arr.reduce((acc, curr) => {
    const isArray = Array.isArray(curr)
    return acc.concat(isArray && depth > 0 ? customFlat(curr, depth - 1) : curr)
  }, [])
}

if (!Array.prototype.customFlat) {
  Array.prototype.customFlat = function (depth = 3) {
    return customFlat(this, depth)
  }
}

console.log([1, 2, [3, 4, [5, 6, [7, [8, 9, 10]]]]].customFlat())
//[1, 2, 3, 4,  5,6, 7, 8, 9, 10]
  1. Closure (Basic problem) Create a function which returns an objet with next() as property. Calling next should return +1 value every time it is called. Like 1,2,3,4…
const closure = () => {
  let a = 0
  return {
    next: () => {
      a = a + 1
      return a
    },
  }
}

const value = closure()

console.log(value.next()) //1
console.log(value.next()) //2
console.log(value.next()) //3
console.log(value.next()) //4
  1. Implement debounce and throttle
//Debounce
const debounce = (fn, delay) => {
  let timer = null

  return (...args) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}

const fn = debounce(() => {
  console.log("Only in one second")
}, 1000)

fn()
fn()
fn()
fn()
fn()

//Throttle
const throttle = (fn, delay) => {
  let allow = true

  return (...args) => {
    if (allow) {
      fn(...args)
      allow = false
      setTimeout(() => {
        allow = true
      }, delay)
    }
  }
}

const fn1 = throttle(() => {
  console.log("Only after one second")
}, 1000)

fn1()
fn1()
fn1()

//Output
// Only after one second
// Only in one second
React.js Handson
  1. Create a commentBox and show the comments list. In Comments list user can reply to a comment till nth level. User can Edit any comment.

Solution

  1. Fetch live data from a cricket score API.

    • Create 3 buttons Start, Pause, Reset
    • Clicking on start should fetch data from API after every 10 seconds and show in browser.
    • Clicking on pause should pause timer.
    • Clicking on reset should reset timer
  2. Design a basic HTML previewer.

  3. Design an accordion with open and close animation. Add props openOne. If it is true then only one accordion should be opened at a time in Accordion Group. If false all can be opened.

  4. Fetch Data from an API and render to a table. Add a checkbox filter. On checking only the records with a field(status) true should come in table.

  5. Design a grid component. It should be reusable and configurable. Add column level sorting and filtering. Add pagination, async data loading and infinite scrolling.

  6. 2 hours assignment: Create a quiz application in React. (Wireframes given) Expected

    1. Timer of 30 seconds.
    2. On click of an option show correct in green and incorrect in red. Wait for 3 seconds before moving to next question.
    3. At last show total score.
  7. Create a 4X4 layout with all the divs clickable and on click show and alert box with x,y coordinates of that div. Improve it by using event delegation. (This was in Vanilla.js) Demo

  8. Create a folder structure where folder should expend and collapse on click and file should not be clickable. Demo

  9. Create a custom RadioWrapper where options can be passed as children but manage state in wrapper. Used useContext. Now Optimize it in such a way that when use click on an option, only options with changing states(prev selected and current selected) should rerender.

  10. Create a tic tac toe game.

  11. Create star rating component We can pass rating in props. Rating can have decimal value to .5 like 1.5, 2.5 Print half star in that case. If I hover on any star, all previous stars should fill and on click persist rating and onblur go to prev rating.

  12. Code a Stopwatch. Three button—> Start , Pause, Reset.

  13. Create a input field. Make an API call(Dummy) when user type. Debounce this API request.


Vishal Sharma

Hey there! This is Vishal Sharma. I reside and work at Gurgaon, India. I am a Software Engineer and primarily works with JavaScript, ReactJS and NodeJS.
LinkedIn Link

Welcome to my Javascript tech blog! Here, you'll find the latest news and updates in the world of Javascript, as well as tutorials and resources to help you improve your coding skills. From learning the basics of Javascript to advanced concepts like object-oriented programming, I post something for developers of all levels. Whether you're just starting out or you're a seasoned pro, you'll find valuable insights and information on our blog. So stay up-to-date with the latest in Javascript technology by bookmarking this page and checking back often.
Thank you for visiting!