How to crack a JavaScript interview

You can prepare for a JavaScript Interview by breaking it down into important topics. If you practice and break the process down, you will be prepared. This guide will cover the most essential things that you should know about each round of an average JavaScript interview.

Round 1: Core JavaScript Concepts

This round is designed to test your knowledge of JavaScript basics.

Closures

Closure occurs when a function remembers its outer variables, even after the outer functions have ended.

Example Question: What is a closure in JavaScript, and how does it work?

function outer() {
  let counter = 0;
  
  function inner() {
    counter++;  // Inner function has access to `counter` from outer function's scope
    console.log(counter);
  }
  
  return inner;
}

const increment = outer();  // `increment` is a closure that has access to `counter`
increment();  // 1
increment();  // 2

Hoisting

JavaScript hoists variable and function declarations up to the top of the scope. To avoid bugs, you need to know how this works.

Example Question: What happens if you use let, var, or cont within a function?

console.log(a);  // undefined (due to hoisting)
var a = 5;

console.log(b);  // ReferenceError: Cannot access 'b' before initialization
let b = 10;

Prototyping Inheritance

JavaScript allows objects to inherit methods and properties from other objects. This is not the same as classical inheritance in different programming languages.

Example Question: How does JavaScript’s prototypical inheritance work?

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayHello = function() {
  console.log(`Hello, I am ${this.name}`);
};

const dog = new Animal('Buddy');
dog.sayHello();  // Hello, I am Buddy

Sets, Maps, WeakMaps and WeakSets

JavaScript has a number of special data structures. Use each data structure correctly.

Example Question: What is the difference between map and weakMap?

Functional Programming/Immutability

Functional programming is focused on functions only and avoids side effects. Immutability is the inability to change data directly.

Example Question: Why is JavaScript’s immutability important?

Round 2: Problem Solving & Polyfills

This round will involve solving coding issues and implementing JavaScript functions that either need to be added or have been custom-built.

Problem-solving (Algorithms)

Solve common problems, such as finding the maximum number of a string, filtering information, or checking whether two strings are anagrams.

Example Question: Write a function that will find the largest number within an array.

Polyfills

It may be necessary to modify JavaScript functions such as map or forEach.

Example Question: Write a polyfill to array.prototype.map.

// Polyfill for Array.prototype.map
if (!Array.prototype.myMap) {
  Array.prototype.myMap = function(callback) {
    const newArr = [];
    for (let i = 0; i < this.length; i++) {
      newArr.push(callback(this[i], i, this));
    }
    return newArr;
  };
}

const arr = [1, 2, 3];
const doubled = arr.myMap(x => x * 2);
console.log(doubled);  // [2, 4, 6]

Here’s a simple problem where we need to find the largest number in an array.

function findLargest(arr) {
  return arr.reduce((max, num) => (num > max ? num : max), arr[0]);
}

const numbers = [4, 5, 1, 12, 7];
console.log(findLargest(numbers));  // 12

Round 3: Machine Coding (React/Vanilla JS)

This round you will need to create small components or projects using React.

Pagination

You may be asked to create a pagination component in order to navigate through data.

A simple React component that handles pagination

import React, { useState } from 'react';

const Pagination = ({ items, itemsPerPage }) => {
  const [currentPage, setCurrentPage] = useState(1);
  
  const totalPages = Math.ceil(items.length / itemsPerPage);
  
  const getCurrentItems = () => {
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    return items.slice(start, end);
  };
  
  return (
    <div>
      <ul>
        {getCurrentItems().map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      
      <div>
        <button onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}>
          Previous
        </button>
        <span> Page {currentPage} of {totalPages} </span>
        <button onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage === totalPages}>
          Next
        </button>
      </div>
    </div>
  );
};

export default Pagination;

Custom Hooks

You’ll need to know how to create custom hooks if you use React to share logic among components.

import { useState } from 'react';

function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return { count, increment, decrement };
}

export default useCounter;

Now you can use this useCounter hook in any component

import React from 'react';
import useCounter from './useCounter';

const CounterComponent = () => {
  const { count, increment, decrement } = useCounter(0);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

export default CounterComponent;

File Explorer

File explorer UIs are a popular project to test your ability to build responsive interfaces and manage state.

Example Project: Create a simple file browser with folders and documents.

Round 4: Performance, Security & Web Fundamentals

This round will test your knowledge of web performance, security, and general concepts.

React.memo is used to prevent unnecessary re-renders of components that don’t change their props.

const ExpensiveComponent = React.memo(({ value }) => {
console.log('Rendering ExpensiveComponent');
return <div>{value}</div>;
});

export default ExpensiveComponent;

Security: XSS and Injection Attacks

Web development is only complete with security. XSS and SQL injection attacks are two common problems you should be aware of and try to prevent.

Example Question: What is an XSS attack, and how can you protect yourself?

import React, { useState } from 'react';
import DOMPurify from 'dompurify';  // DOMPurify is a popular library for sanitizing HTML

const CommentForm = () => {
  const [comment, setComment] = useState('');

  const handleChange = (e) => {
    setComment(DOMPurify.sanitize(e.target.value));
  };

  return (
    <div>
      <textarea value={comment} onChange={handleChange}></textarea>
      <div dangerouslySetInnerHTML={{ __html: comment }}></div>
    </div>
  );
};

export default CommentForm;

Babel & Webpack

Babel and Webpack allow you to write JavaScript that is modern and optimized. Learn how these tools can improve your application.

Example Question: What is Webpack, and how does Webpack optimize web applications for users?

React performance optimization

It is important to understand how to speed up React applications using techniques such as React. Memo and useMemo.

Core Web Vitals and Performance

Core Web Vitals (like The Largest Contentful Painting) measure your website’s performance. It is important to know how to optimize them.

Example Question: What are Core Web Vitals, and how can you optimize them for your website?

Round 5: Miscellaneous Topics

This round could cover HTML, CSS, and Design Patterns.

HTML/CSS

Be sure to know HTML structure and CSS layouts, such as Flexbox.

Design Patterns

Software design patterns offer common solutions for recurring issues. You should be familiar with patterns such as Singleton Factory and Observer.

New JavaScript features (ES7 to 13)

JavaScript is constantly evolving. Be familiar with the new features, such as optional chains and nullish coagulation.

HTTP Request Types

You can learn about the different types of content in HTTP requests, such as application/JSON and multipart/form data.

Example Question: What is the difference between form data and application/JSON?

CDNs

Content Delivery Networks (CDNs), which serve assets closer to users, can help your website load faster.

Example Question: What is a CDN?

Final Tips for Success

  • Practice Coding: Solve problems using platforms such as LeetCode, HackerRank, or Codewars.
  • Understanding the Basics: Ensure you are familiar with JavaScript fundamentals like closures, hoisting, and prototypes.
  • Build Projects Hands-on Experience is essential. To solidify your understanding, build projects using React or vanilla JavaScript.
  • Optimize Performance: Learn to optimize your web application’s performance.
  • Learn Security Best Practices: Become familiar with the common security risks and learn how to avoid them.

Conclusion

You can prepare for the JavaScript interview by breaking it down into manageable rounds. This will allow you to focus on what is most important. You should practice problem-solving, learn core concepts, and gain hands-on experience in coding. You’ll be more confident when you go for your interview if you have more practice!

Scroll to Top