## Table of contents

- 1. Reverse a String
- 2. Find the Factorial of a Number
- 3. Check for Palindromes
- 4. Fibonacci Sequence
- 5. Flatten a Nested Array
- 6. Find the Maximum Element in an Array
- 7. Merge Two Sorted Arrays
- 8. Remove Duplicates from an Array
- 9. Implement a Queue Using Two Stacks
- 10. Check if Two Strings Are Anagrams
- Conclusion

**Introduction**

Preparing for a JavaScript interview can be challenging, especially when coding snippets and problem-solving skills play a crucial role in the selection process. While having a solid understanding of JavaScript fundamentals is essential, interviewers often test your problem-solving abilities with specific code patterns and real-world scenarios. In this article, we'll explore the top 10 JavaScript coding snippets you need to master for your next interview. We'll also break down each example, discuss optimization techniques, and dive into time complexity analysis to help you stand out in your interview.

**1. Reverse a String**

Reversing a string is one of the most common JavaScript interview questions. Here’s a quick and efficient way to solve this:

```
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // "olleh"
```

**Explanation:**

`split('')`

: Converts the string into an array of characters.`reverse()`

: Reverses the order of the array.`join('')`

: Joins the array back into a string.

**Time Complexity:**

The time complexity of this solution is **O(n)**, where **n** is the length of the string. Each method (`split`

, `reverse`

, and `join`

) iterates through the string once.

**2. Find the Factorial of a Number**

Factorial is the product of an integer and all the integers below it. Here's a recursive solution:

```
function factorial(num) {
if (num === 0) return 1;
return num * factorial(num - 1);
}
console.log(factorial(5)); // 120
```

**Explanation:**

The base case occurs when

`num`

is 0, returning 1.The recursive call multiplies

`num`

by the factorial of`num - 1`

.

**Time Complexity:**

The time complexity is **O(n)**, where **n** is the number input.

**3. Check for Palindromes**

A palindrome is a word, phrase, or sequence that reads the same backward as forward.

```
function isPalindrome(str) {
let cleanedStr = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
return cleanedStr === cleanedStr.split('').reverse().join('');
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
```

**Explanation:**

`replace(/[^A-Za-z0-9]/g, '')`

: Removes non-alphanumeric characters.`toLowerCase()`

: Converts the string to lowercase.The cleaned string is compared with its reverse.

**Time Complexity:**

The time complexity is **O(n)** due to the string reversal.

**4. Fibonacci Sequence**

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones.

```
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(5)); // 5
```

**Explanation:**

The base case occurs when

`n`

is less than or equal to 1.Recursive calls compute the Fibonacci value by summing the two previous numbers.

**Time Complexity:**

The time complexity is **O(2^n)** due to repeated calculations. Memoization or an iterative approach can optimize it to **O(n)**.

**5. Flatten a Nested Array**

This question tests your ability to manipulate arrays.

```
function flattenArray(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}
console.log(flattenArray([1, [2, [3, 4], 5], 6])); // [1, 2, 3, 4, 5, 6]
```

**Explanation:**

`reduce()`

iterates over the array, recursively concatenating nested arrays.`Array.isArray()`

checks if the current element is an array.

**Time Complexity:**

The time complexity is **O(n)**, where **n** is the total number of elements in the array, including nested elements.

**6. Find the Maximum Element in an Array**

Finding the largest number in an array is a common question.

```
function findMax(arr) {
return Math.max(...arr);
}
console.log(findMax([1, 3, 7, 2, 9])); // 9
```

**Explanation:**

The spread operator (

`...`

) expands the array into individual elements.`Math.max()`

returns the largest of the given numbers.

**Time Complexity:**

The time complexity is **O(n)** as `Math.max()`

iterates over all elements.

**7. Merge Two Sorted Arrays**

Merging two sorted arrays is often asked to test your understanding of sorting and merging logic.

```
function mergeArrays(arr1, arr2) {
let merged = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged.push(arr1[i]);
i++;
} else {
merged.push(arr2[j]);
j++;
}
}
return merged.concat(arr1.slice(i)).concat(arr2.slice(j));
}
console.log(mergeArrays([1, 3, 5], [2, 4, 6])); // [1, 2, 3, 4, 5, 6]
```

**Explanation:**

- Use two pointers (
`i`

,`j`

) to compare elements from both arrays and merge them in sorted order.

**Time Complexity:**

The time complexity is **O(n + m)**, where **n** and **m** are the lengths of the two arrays.

**8. Remove Duplicates from an Array**

Removing duplicates from an array is another common coding challenge.

```
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
```

**Explanation:**

`new Set()`

removes duplicate values since sets cannot contain duplicates.The spread operator converts the set back to an array.

**Time Complexity:**

The time complexity is **O(n)**, as `Set`

operates in linear time.

**9. Implement a Queue Using Two Stacks**

This question demonstrates your understanding of data structures.

```
class Queue {
constructor() {
this.stack1 = [];
this.stack2 = [];
}
enqueue(value) {
this.stack1.push(value);
}
dequeue() {
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
}
}
let q = new Queue();
q.enqueue(1);
q.enqueue(2);
console.log(q.dequeue()); // 1
console.log(q.dequeue()); // 2
```

**Explanation:**

`enqueue()`

: Pushes elements to`stack1`

.`dequeue()`

: Transfers elements from`stack1`

to`stack2`

for FIFO behavior.

**Time Complexity:**

Both `enqueue`

and `dequeue`

operations have an average time complexity of **O(1)** due to amortized analysis.

**10. Check if Two Strings Are Anagrams**

An anagram is a word formed by rearranging the letters of another word.

```
function areAnagrams(str1, str2) {
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(areAnagrams("listen", "silent")); // true
console.log(areAnagrams("hello", "world")); // false
```

**Explanation:**

`split('')`

: Converts the string into an array of characters.`sort()`

: Sorts the characters alphabetically.`join('')`

: Joins the sorted characters back into a string.

**Time Complexity:**

The time complexity is **O(n log n)** due to the sorting step.

**Conclusion**

Mastering these JavaScript coding snippets will prepare you for various coding challenges during your interview. From string manipulations to working with arrays and data structures, these examples represent common patterns and logic that interviewers expect candidates to know. Beyond solving the problems, it's crucial to understand time complexity and optimization techniques to impress your interviewers. By practicing these problems and analyzing their efficiency, you'll be well-prepared to ace your JavaScript interview.