# JavaScript String Methods & Polyfills

## What String Methods Are

String methods are **built-in functions** provided by JavaScript to operate on string data.

Examples:

*   `toUpperCase()`
    
*   `slice()`
    
*   `indexOf()`
    
*   `trim()`
    
*   `split()`
    

### Key Property

Strings in JavaScript are **immutable**:

*   Methods do not modify the original string
    
*   They return a **new string**
    

```javascript
const str = "hello";
const result = str.toUpperCase();

console.log(str);     // "hello"
console.log(result);  // "HELLO"
```

## Conceptual Working of String Methods

Internally, most string methods operate using:

*   Iteration over characters
    
*   Index-based access
    
*   Conditional logic
    

### Example: `toUpperCase()`

```javascript
function toUpperCasePolyfill(str) {
  let result = "";

  for (let i = 0; i < str.length; i++) {
    let char = str[i];

    // Convert ASCII lowercase to uppercase
    if (char >= 'a' && char <= 'z') {
      result += String.fromCharCode(char.charCodeAt(0) - 32);
    } else {
      result += char;
    }
  }

  return result;
}
```

### Insight

*   Built-in methods are optimized in engines (V8, SpiderMonkey)
    
*   But logic remains **loop + transformation**
    

## Why Developers Write Polyfills

### Definition

A **polyfill** is a custom implementation of a method that mimics native behavior.

### Reasons

1.  **Browser compatibility**
    
    *   Older browsers may not support modern methods
        
2.  **Understanding internals**
    
    *   Helps in interviews and debugging
        
3.  **Control over behavior**
    
    *   Custom edge-case handling
        

## Implementing Simple String Utilities (Polyfills)

includes()

```javascript
function includesPolyfill(str, search) {
  for (let i = 0; i <= str.length - search.length; i++) {
    let match = true;

    for (let j = 0; j < search.length; j++) {
      if (str[i + j] !== search[j]) {
        match = false;
        break;
      }
    }

    if (match) return true;
  }
  return false;
}
```

reverse()

```javascript
function reverseString(str) {
  let result = "";

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

  return result;
}
```

trim()

```javascript
function trimPolyfill(str) {
  let start = 0;
  let end = str.length - 1;

  while (str[start] === ' ') start++;
  while (str[end] === ' ') end--;

  let result = "";
  for (let i = start; i <= end; i++) {
    result += str[i];
  }

  return result;
}
```
