# String Polyfills and Common Interview Methods in JavaScript

String methods like `split`, `slice`, and `trim` are things you use every day. But during interviews, you might be asked to implement them from scratch. That's where understanding polyfills matters—it's not about memorizing answers, it's about understanding how things work under the hood.

## What Are String Methods?

JavaScript provides built-in methods for working with strings:

```javascript
const text = "Hello, World!";

text.slice(0, 5);    // "Hello"
text.split(",");     // ["Hello", " World!"]
text.toUpperCase();  // "HELLO, WORLD!"
text.trim();         // "Hello, World!" (no surrounding spaces)
```

These methods do the heavy lifting so you don't have to write the logic yourself.

## Why Write Polyfills?

A polyfill is a custom implementation of a built-in method. You might write one because:

1.  **Browser support** – Old browsers don't have modern methods, so you provide a fallback
    
2.  **Interview preparation** – Recruiters want to see you understand the underlying logic
    
3.  **Learning** – Implementing something yourself reveals how it actually works
    

Writing polyfills isn't something you'd do in production (the built-in methods are faster and tested). But going through the exercise makes you a better developer.

## Implementing Common String Methods

Let's build simplified versions of popular string methods.

### slice()

`slice(start, end)` returns characters from index `start` up to (but not including) `end`:

```javascript
String.prototype.mySlice = function(start, end) {
  let result = '';
  const str = this;
  
  // Handle negative indices
  if (start < 0) start = str.length + start;
  if (end < 0) end = str.length + end;
  
  // Clamp values
  start = Math.max(0, start);
  end = Math.min(str.length, end);
  
  // Extract characters
  for (let i = start; i < end; i++) {
    result += str[i];
  }
  
  return result;
};

"Hello".mySlice(1, 4); // "ell"
```

### trim()

`trim()` removes whitespace from both ends:

```javascript
String.prototype.myTrim = function() {
  let start = 0;
  let end = this.length - 1;
  
  // Find first non-space character
  while (start <= end && this[start] === ' ') {
    start++;
  }
  
  // Find last non-space character
  while (end >= start && this[end] === ' ') {
    end--;
  }
  
  // Return substring
  return this.substring(start, end + 1);
};

"  hello  ".myTrim(); // "hello"
```

### reverse()

Not a built-in, but common in interviews:

```javascript
String.prototype.reverse = function() {
  return this.split('').reverse().join('');
};

"hello".reverse(); // "olleh"
```

## Common Interview String Problems

Here are patterns that come up often:

**Palindrome check:**

```javascript
function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return cleaned === cleaned.split('').reverse().join('');
}
```

**Character frequency:**

```javascript
function charCount(str) {
  const counts = {};
  for (const char of str) {
    counts[char] = (counts[char] || 0) + 1;
  }
  return counts;
}
```

**Anagram detection:**

```javascript
function isAnagram(a, b) {
  const normalize = s => s.toLowerCase().split('').sort().join('');
  return normalize(a) === normalize(b);
}
```

## Why Understanding Built-in Behavior Matters

Here's the thing: knowing what methods exist isn't enough. You need to know:

*   What happens with edge cases (empty strings, negative indices, out-of-bounds)
    
*   What the method returns (new string? the same one? undefined?)
    
*   How it handles different types (what if you pass a number?)
    

```javascript
"hello".slice(-2);   // "lo" - negative works
"hello".slice(10);   // "" - out of bounds returns empty
"hello".slice(2, 1); // "" - start > end returns empty
```

These nuances matter when debugging, and interviewers love drilling into them.

## Wrapping Up

Polyfills teach you how to think about string manipulation at a fundamental level. You don't need to memorize implementations, but you should understand the logic behind methods like `slice`, `split`, `trim`, and `indexOf`.

When you understand how something works internally, you use it more effectively. You'll catch bugs faster, write cleaner code, and ace those implementation questions.
