Sagar Deep Kushwaha

Sagar Deep Kushwaha

Published in technology* 24 April 2024 * 5 min read

6 Must Revise Javascript coding interview questions before any interview

6-must-know-javascript-interview-questions.png
Javascript
Are you gearing up for a JavaScript interview and feeling the nerves creeping in? Don't worry, you're not alone. Interviews can be intimidating, but with the right preparation, you can ace them with confidence. JavaScript interviews. Let's delve into the top 6 must know coding questions you must revise before stepping into that interview room.

Chapters

  • Intro
  • What will you learn
  • Sleep fuinction
  • Flatten an array
  • Polyfill of Call, Bind and Apply
  • Debounce and Throttle functions
  • Polyfill for promise.all
  • Currying functions
  • Conclusion

Intro

I have more than 4 years of frontend development experience. I have given more than 50+ interviews when . I have experienced apart from traditional questions like, event loop, closures, prototypal inheritance. Interviewer mostly ask these type of questions which checks your understanding of Promises, Optimizing function call, How helper functions work behind the scene.

What will you learn

These are the 6 basic questions which you must know before going to any javascript coding round they will be helpful in any case.

  1. Sleep function
  2. Flatten an array
  3. Polyfill of Call, Bind and Apply
  4. Debounce and Throttle
  5. Polyfill of Promise.all
  6. Currying functions

Sleep fuinction

Question: Can you explain how to create a sleep function in JavaScript?

Answer: Sleep function is an asynchronous function which can be used to make some task to wait for some time. To implement a sleep function in JavaScript, you can use a combination of setTimeout and Promise.

Here's a simple example:

 

function sleep(delay) { return new Promise(resolve => setTimeout(resolve, delay)); }

Flatten an array

Question: How would you flatten an array or a nested object in JavaScript?
Answer: You can flatten an array using recursion or methods like reduce. For nested objects, recursion is typically used. This question checks if user is familiar with modern javascript syntax and methods..

 

Here's a basic approach for flattening an array:

 

function flattenArray(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []); }

 

Extended version : Flatten an array upto certain level

function flattenArrayWithLevel(arr, level) { return arr.reduce((acc, curr) => { if (Array.isArray(curr) && level > 0) { acc.push(...flattenArrayWithLevel(curr, level - 1)); return acc; } acc.push(curr); return acc; }, []); }

Polyfill of Call, Bind and Apply

Question: Can you provide a polyfill for the call, bind, and apply methods in JavaScript?

Answer: Polyfills for these methods enable backward compatibility with older JavaScript environments.

 

First let's see how each function works.

 

const person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + ", " + city + ", " + country; } }; const person1 = { firstName: "John", lastName: "Doe" }; console.log(person.fullName.call(person1, "New York", "USA")); // Output: John Doe, New York, USA console.log(person.fullName.apply(person1, ["New York", "USA"])); // Output: John Doe, New York, USA const bindCall = person.fullName.bind(person1, "New York"); console.log(bindCall("USA")); // Output: John Doe, New York, USA

 

Let's break it and create a basic polyfill of all

 

1. Call: Call function takes a reference object and extra parameters which are passed to the function on which we are calling the call;

 

Function.prototype.myCall =function(context,...args){ context.myRef = this; // Defining a property onto refObject i.e. ***context*** and ***this*** is pointing to function itself context.myRef(...args); // Path the parameters to this function }

 

2. Apply: The apply method is same as the call method but the only difference is it takes the parameters as an Array.

 

Function.prototype.myApply =function(context,[args]){ context.myRef = this; // Defining a property onto refObject i.e. ***context*** and ***this*** is pointing to function itself context.myRef(...args); // Path the parameters to this function }

 

3. Bind: The bind method returns a copy of original function with context which was passed.

 

Function.prototype.myBind =function(context,...args1){ return function(...args2){ Function.apply(context, [...args1,...args2]); } }

Debounce and Throttle functions

Question: Explain the concepts of debounce and throttle functions, and when to use each.
Answer: Debounce and Throttle functions both are used to restrict the number of unnecessary function calls.

 

Debounce : Debouncing ensures a function is only called after a certain period of inactivity. Debouncing is useful for events like input changes, mouse click events, autosave in text editors .

 

function debounce(callback, delay){ let timer ; return function(...args){ clearTimeout(timer); timer = setTimeout(() => { callback(...args); }, delay) } }

 

Throttle: Throttling typically involves setting a fixed interval between function calls or restricting the function calls between intervals. Throttling is useful for events like scroll, Shooting games i.e. Triggering shoot button.

 

function throttle(callback, delay){ let shouldRun = true; let timer; return function(...args){ if(shouldRun){ shouldRun = false; callback(...args); clearTimeout(timer); timer = setTimeout(() => { shouldRun = true; }, delay); } } }

Polyfill for promise.all

Question: How would you create a polyfill for Promise.all using async/await and then/catch?

Answer: Promise.all function takes an array of promises and return the promise when either all the promises are resolved or an promise is rejected. The response is array of result of promises in order of they are passed.

 

Here's is an basic polyfill for Promise.all

 

//Polyfill function promiseAll(promises) { return new Promise(async (res, rej) => { const ansArr = []; for (let x = 0; x < promises.length; x++) { try { const data = await promises[x]; ansArr[x] = data; if (x === promises.length - 1) res(ansArr); } catch (e) { rej(e) } } }) } function wait(delay, value = '') { return new Promise((resolve, reject) => { setTimeout(() => { resolve(value); }, delay) }) } //Test function async function Test(promises) { try { const ans = await promiseAll(promises); console.log({ ans }); } catch (e) { console.log(e); } } const promises1 = [1, 2, Promise.resolve(3), wait(300, 4), wait(200, 5), wait(100, 6)]; const promises2 = [1, Promise.reject(2), Promise.resolve(3), wait(300, 4), wait(200, 5), wait(100, 6)]; Test(promises1); Test(promises2);

Currying functions

Question: Explain the concept of currying in JavaScript and provide an example.

Answer: It is a concept of functional programming through which we can transform a function with multiple parameters into a nesting sequence of function, each taking one argument.

 

function sumUptoN(n) { // Base case: If n is 0, return 0 if (n === 0) { return 0; } else { // Return a function that takes the next argument return function(next) { // If next argument is provided, add it to n and return the sum if (next !== undefined) { return sumUptoN(n + next); } else { // If next argument is not provided, return the current sum return n; } }; } } // Usage examples: console.log(sumUptoN(1)(2)(3)()); // Output: 6 (1 + 2 + 3 = 6) console.log(sumUptoN(5)(5)(5)(5)(5)(5)()); // Output: 30 (5 + 5 + 5 + 5 + 5 + 5 = 30) console.log(sumUptoN(10)(20)(30)(40)()); // Output: 100 (10 + 20 + 30 + 40 = 100)

Conclusion

Preparing for a JavaScript interview can be daunting, but focusing on fundamental coding questions can significantly boost your confidence. By revisiting these top 6 coding questions and practicing regularly, you'll sharpen your understanding of javascript.

More articles

Dive into the world of TypeScript, the superset of JavaScript that brings static typing and advanced features to web development.

In today's JavaScript landscape, Promises are essential for asynchronous programming. However, older browsers often lack native support for Promises, necessitating the use of polyfills. In this comprehensive guide, we'll delve into Promise polyfills, explaining their importance and demonstrating their usage with practical examples.

Chapters

  • Intro
  • What will you learn
  • Sleep fuinction
  • Flatten an array
  • Polyfill of Call, Bind and Apply
  • Debounce and Throttle functions
  • Polyfill for promise.all
  • Currying functions
  • Conclusion

Top articles

Demystifying TypeScript: Exploring Its Core Concepts and Features

Dive into the world of TypeScript, the superset of JavaScript that brings static typing and advanced features to web development.

Mastering JavaScript Promise Polyfill: A Complete Guide with Examples

In today's JavaScript landscape, Promises are essential for asynchronous programming. However, older browsers often lack native support for Promises, necessitating the use of polyfills. In this comprehensive guide, we'll delve into Promise polyfills, explaining their importance and demonstrating their usage with practical examples.