Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Interview Methods in JavaScript

Updated
7 min readView as Markdown
String Polyfills and Common Interview Methods in JavaScript
A

I like making things with code. This is where I share my projects and the bugs I ran into.

Every Indian grows up on jugaad. The mixer dies right before dinner, so you crush the masala with a belan. Your charger cable stops working unless you hold it at one exact angle, so you prop a book on top of it. The ready-made tool is missing or broken, so you build your own little solution that gets the job done. Bas, jugaad ho gaya.

Turns out JavaScript developers do jugaad too, and it even has a respectable name. A polyfill. When a built-in method is not available in some environment, an old browser, for example, you write your own version that behaves exactly like the real one. That is, no exaggeration, jugaad for a missing method.

And there is a lovely side effect. The moment you build a method yourself instead of just calling it, you finally understand what it was actually doing all along. Which is exactly why interviews love making you do this. So in this post we will do both, write our own versions of string methods, and then crack the common string interview problems that check whether you truly get it. Chalo shuru karte hain.

First, what even are string methods

String methods are the ready-made tools JavaScript already gives you to work with text. You use them every day without thinking.

const name = "  Ayush  ";

name.trim();             // "Ayush"      removes the spaces around it
name.toUpperCase();      // "  AYUSH  "  shouts it
"hello".includes("ell"); // true         is this piece inside?
"a,b,c".split(",");      // ["a","b","c"] break it into an array

These are the built-ins, the factory tools. Most of the time you just call them and move on. But two situations change that, either the tool is not available where your code runs, or an interviewer takes the tool away to see if you can build it yourself. Both lead to the same skill, so let us build.

What a polyfill is, and why anyone writes one

A polyfill is your own implementation of a built-in feature, written so your code still works in an environment that does not have that feature yet.

Rewind a few years. Methods we now take for granted, like includes or padStart, simply did not exist in older browsers. So if you used includes and someone opened your site on a purana browser, it would crash. Developers solved this with jugaad, they wrote their own includes and quietly added it only if the browser was missing it.

Here is that exact pattern.

if (!String.prototype.includes) {
  String.prototype.includes = function (search) {
    return this.indexOf(search) !== -1;
  };
}

Read it slowly. if (!String.prototype.includes) means "if strings do not already have an includes method." Only then do we add our own, using indexOf, which is older and always available. If the browser already has includes, we do not touch it. That is a polyfill, jugaad that activates only when the real tool is missing.

And notice what building it forced you to realise, that includes is really just indexOf checking whether the result is not -1. You will never look at includes the same way again. That understanding is the whole point.

Building your own string utilities

Sometimes it is not even about missing methods, it is just that JavaScript never gave you the tool at all. Take capitalising a word. There is no built-in capitalize, so everyone writes their own.

function capitalize(str) {
  return str[0].toUpperCase() + str.slice(1);
}

capitalize("ayush"); // "Ayush"

Grab the first character, upper-case it, then glue the rest of the string back on with slice(1). Chhota sa jugaad, but you will use it constantly.

Want to capitalise every word in a sentence? Split, capitalise each, join back.

function titleCase(sentence) {
  return sentence
    .split(" ")
    .map((word) => capitalize(word))
    .join(" ");
}

titleCase("jai shri krishna"); // "Jai Shri Krishna"

See how the small tool you built becomes a building block for a bigger one. That is exactly how real code grows.

The common interview string problems

Now the part interviews actually hammer you on. These show up again and again, so let us walk through the classics. And a fair warning, interviewers will often say "without using the fancy built-ins," so it helps to know the logic, not just the shortcut.

Reverse a string

The shortcut everyone knows first.

function reverse(str) {
  return str.split("").reverse().join("");
}

Split into characters, reverse the array, join back. But if they take reverse() away, do it by hand, walking the string backwards.

function reverse(str) {
  let result = "";
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }
  return result;
}

reverse("ayush"); // "hsuya"

Check for a palindrome

A palindrome reads the same forwards and backwards, like "level" or "madam." So just compare the string with its own reverse.

function isPalindrome(str) {
  const clean = str.toLowerCase();
  return clean === reverse(clean);
}

isPalindrome("Madam"); // true
isPalindrome("hello"); // false

Notice we reused our own reverse from above. Chhote tools, bade kaam.

Count the vowels

Loop through, check each character against the vowels.

function countVowels(str) {
  let count = 0;
  for (const ch of str.toLowerCase()) {
    if ("aeiou".includes(ch)) count++;
  }
  return count;
}

countVowels("Ayush Jain"); // 4

First non-repeating character

A real favourite. Find the first character that appears exactly once. The trick is to count every character first, then scan again for the first one with a count of 1.

function firstUnique(str) {
  const freq = {};

  for (const ch of str) {
    freq[ch] = (freq[ch] || 0) + 1;
  }

  for (const ch of str) {
    if (freq[ch] === 1) return ch;
  }

  return null;
}

firstUnique("aabbc"); // "c"

Two passes, one to count, one to find. This "count first, then decide" pattern comes up in a lot of string questions, so keep it in your pocket.

Anagram check

Two words are anagrams if they use the exact same letters, like "listen" and "silent." The cleanest trick, sort both and see if they match.

function isAnagram(a, b) {
  const clean = (s) => s.toLowerCase().split("").sort().join("");
  return clean(a) === clean(b);
}

isAnagram("listen", "silent"); // true
isAnagram("hello", "world");   // false

If the same letters are present in both, sorting lines them up identically. Simple and effective.

Why understanding the built-ins matters so much

Here is the honest reason all of this is worth your time. When you know that includes is just indexOf, that a palindrome is just a string equal to its reverse, that finding a unique character is just counting then scanning, you stop being a developer who only memorises method names. You become one who understands what is happening underneath.

That is the exact difference interviewers are hunting for. Anyone can type str.reverse. They want to see if you can rebuild it when the shortcut is gone. And in real work, that same understanding is what lets you debug the weird edge case at 2 in the morning when a built-in behaves in a way you did not expect.

Try it yourself

Do not just read it, khud likho. Paste this in and play.

function reverse(str) {
  return str.split("").reverse().join("");
}

function isPalindrome(str) {
  const clean = str.toLowerCase();
  return clean === reverse(clean);
}

console.log(reverse("krishna"));       // "anhsirk"
console.log(isPalindrome("nitin"));    // true
console.log(isPalindrome("ayush"));    // false

Now try the tough ones from memory, write firstUnique and isAnagram again without looking. That struggle is the actual practice, not the reading.

Wrapping up

So that is the whole idea. A polyfill is jugaad for a missing method, you rebuild the built-in yourself so your code keeps working, and in doing so you finally understand how that method really behaves. The common interview problems, reverse, palindrome, vowels, first unique, anagram, are all just the same skill, understanding strings deeply enough to build the logic by hand.

The next time a mixer dies and you reach for a belan, remember, you are a natural at polyfills. You have been doing jugaad your whole life, this is just the JavaScript version.

And if building your own methods felt good here, you already got a taste of it in the last post where we hand-rolled our own array flatten. Same energy, same interview reward.

I hope you enjoyed reading this.