JavaScript Interview Questions 46-50 (ES6 Features, Memoization, Tree-shaking)

Welcome to this focused session on Modern JavaScript (ES6+) and performance optimization. In this lesson, we will cover the "syntactic sugar" that makes writing JavaScript a joy today compared to a decade ago.

We will look at cleaner ways to handle strings and variables, how to merge and extract data effortlessly, and two high-level concepts—Memoization and Tree-shaking—that make your applications faster and lighter. Let's dive in.

46. What are template literals in JavaScript?

Template literals are a feature introduced in ES6 that provides an easier way to create strings. Instead of using single or double quotes, you use backticks (`). They allow for embedded expressions (interpolation) and multi-line strings without needing complex concatenation.

Analogy:
Old Strings: Like cutting words out of a magazine and gluing them together to make a ransom note (Concatenation: "Hello " + name + "!").
Template Literals: Like a "Mad Libs" form where you just fill in the blanks directly on the page (`Hello ${name}!`).

const name = "Alice";
const age = 25;

// Old way (Concatenation)
const oldGreeting = "Hello, my name is " + name + " and I am " + age + ".";

// New way (Template Literal)
const newGreeting = `Hello, my name is ${name} and I am ${age}.`;

// Multi-line support
const poem = `Roses are red,
Violets are blue,
Template literals are cool,
And so are you.`;

console.log(newGreeting);
console.log(poem);

Sample Output:

Hello, my name is Alice and I am 25.
Roses are red,
Violets are blue,
Template literals are cool,
And so are you.

47. What is destructuring in JavaScript?

Destructuring is a syntax that allows you to "unpack" values from arrays or properties from objects into distinct variables. It saves you from writing repetitive code like const name = user.name over and over.

Analogy: Imagine you have a fully packed suitcase (an Object).
Without Destructuring: You carry the entire suitcase around the room, unzip it, take out a shirt, zip it, carry it to the mirror, unzip it, take out a comb.
With Destructuring: You open the suitcase once at the start, take out exactly what you need (Shirt, Comb), and just hold those items directly.

// 1. Object Destructuring
const user = {
  id: 101,
  username: "coder_jane",
  role: "admin"
};

// Extract properties into variables of the same name
const { username, role } = user;

console.log(username); // "coder_jane"
console.log(role);     // "admin"

// 2. Array Destructuring
const colors = ["red", "green", "blue"];

// Unpack based on position
const [firstColor, secondColor] = colors;

console.log(firstColor);  // "red"
console.log(secondColor); // "green"

Sample Output:

coder_jane
admin
red
green

48. What is the spread operator and rest operator?

Both operators use the same syntax: three dots (...). The difference depends on where you use them.

FeatureSpread OperatorRest Operator
ActionExpands / UnpacksCollects / Packs
UsageFunction calls, Array literalsFunction arguments
AnalogySpreading butter on toast (expanding)Cleaning up toys into a box (collecting the rest)
// --- SPREAD (Expanding) ---
const fruits = ["apple", "banana"];
const moreFruits = ["cherry", ...fruits]; // Spread 'fruits' inside new array
console.log(moreFruits); // ["cherry", "apple", "banana"]

const obj1 = { foo: "bar" };
const obj2 = { ...obj1, baz: "qux" }; // Spread object properties
console.log(obj2); // { foo: "bar", baz: "qux" }


// --- REST (Collecting) ---
// Collects "the rest" of the arguments into an array
function sumAll(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sumAll(1, 2, 3, 4)); // 10

Tip: The Rest operator must always be the last parameter in a function definition, because it collects everything remaining.

49. What is memoization in JavaScript?

Memoization is an optimization technique. It involves caching the result of an expensive function call so that the next time the function is called with the same arguments, the cached result is returned instead of recalculating it.

Analogy: Imagine asking a librarian a very difficult trivia question.
First time: They have to walk to the archives, search through books, and find the answer. It takes 10 minutes. (Computation).
Second time: You ask the exact same question. They remember the answer immediately. It takes 1 second. (Memoization).

// Simple Memoization Helper
const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache[key]) {
      console.log("Fetching from cache for:", args);
      return cache[key];
    } else {
      console.log("Calculating result for:", args);
      const result = fn(...args);
      cache[key] = result;
      return result;
    }
  };
};

const slowSquare = (n) => n * n;
const fastSquare = memoize(slowSquare);

console.log(fastSquare(5)); // Calculates
console.log(fastSquare(5)); // Returns cached
console.log(fastSquare(6)); // Calculates new input

Sample Output:

Calculating result for: [ 5 ]
25
Fetching from cache for: [ 5 ]
25
Calculating result for: [ 6 ]
36

50. What is tree-shaking in modern JavaScript build systems?

Tree-shaking is a term used by modern build tools (like Webpack, Rollup, or Vite) to remove unused code from the final bundle. It relies on the static structure of ES Modules (import/export) to detect which parts of your code are never actually used and drops them.

Analogy: Imagine a tree (your application code). Some branches are green and alive (code you are using). Some branches are brown and dead (code you wrote or imported but aren't using).
The build tool grabs the tree and shakes it violently. The dead branches fall off, leaving a lighter, smaller tree to ship to the user.

// --- mathUtils.js ---
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

// --- main.js ---
import { add } from './mathUtils.js';

console.log(add(5, 10));

// Note: We NEVER imported or used 'subtract'.
// During the build process (Tree-shaking), the 'subtract' function 
// will be physically removed from the final bundle file.
// This keeps the website loading fast.

You have successfully completed 50 JavaScript interview questions! We started from simple variables and data types, moved through the event loop and DOM, and finished with advanced performance techniques and modern syntax.

Review these concepts often. The goal isn't just to memorize the code, but to understand the reasoning behind it—why we use memoization, why we use tree-shaking, and how destructuring makes our lives easier. Good luck with your interviews; you are well-prepared!

🚀 Deep Dive With AI Scholar