# String Polyfills and Common Interview Methods in JavaScript

**Methods** in JavaScript (and other languages) help us perform specific actions, allowing us to modify, manipulate, or perform checks on data like strings and arrays.

#### String Methods

String methods specifically help us work with strings, whether that is changing the case, searching for characters, or measuring length.

#### Polyfills

Sometimes we want to use a modern method, but certain older browsers don't support it. That’s when we create our own version of that method from scratch

**For example:** Let's create a method similar to `.length` called `getLength()` that counts the characters in any string.

```javascript
function getLength(){
    let cnt=0;
    for (let i = 0; i < this.length; i++) {
        cnt++
    }
    return cnt;
}
```

#### Usage: Modifying the Prototype

To use this, we add it to the `String.prototype`.

```javascript
// modify prototype
String.prototype.getLength = getLength;

// can use in such a way
console.log("lemon".getLength())
```

* * *

**Common Problems** -  
To test the logic and perform a task **without** using the built-in methods (like `.reverse()`).

writing a function to **reverse a string**

```javascript
function giveReverse(){
    let givenStr = this.split("");
    
    //init array with same length as given str
    let newStr = new Array(this.length);

    let last = 0; // a pointer to start from end
    for (let i = this.length; i >= 0; i--) {
        // in new str start place from the end(last)
        newStr[i] = givenStr[last]
        last++;
    }

    return newStr.join("")
}

//usage
String.prototype.giveReverse = giveReverse;
console.log("lemon".giveReverse()); // "nomel"
```

this can be now used further and checking something like a **palindrome** becomes a one liner

```javascript
console.log("tangent" === "tangent".giveReverse())
```

**Importance** -

**Learning the logic under the hood**  
From the above, we've learned more than just syntax by focusing on the **underlying logic**. Working on problems like these helps understand:

*   **Memory Management:** Learning to initialize an array with a specific size instead of letting it grow randomly.
    
*   **Immutability:** Truly grasping that can't "edit" a string, have to build a brand new one.
    
*   **Efficiency:** Seeing exactly how many steps the computer takes to move a single letter from one end to the other.
