Comprehensive JavaScript Coding Interview Practice

 

. Array Methods

a. map()
Transform each element in an array.

javascript
const numbers = [1, 2, 3];
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9]

b. filter()
Select elements that satisfy a condition.

javascript
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2]

c. reduce()
Reduce an array to a single value.

javascript
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 6

d. find() / findIndex()
Find the first match.

javascript
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2

const firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
console.log(firstEvenIndex); // 1

e. some() / every()
Check if any/all elements meet a condition.

javascript
const hasNegative = numbers.some(num => num < 0); // false
const allPositive = numbers.every(num => num > 0); // true

f. flat()
Flatten nested arrays.

javascript
const nested = [1, [2, 3], [4, [5]]];
console.log(nested.flat(2)); // [1, 2, 3, 4, 5]

2. String Methods

a. split() / join()
Convert between strings and arrays.

javascript
const str = "hello world";
const words = str.split(" "); // ["hello", "world"]
const newStr = words.join("-"); // "hello-world"

b. includes() / startsWith() / endsWith()
Check substrings.

javascript
console.log(str.includes("world")); // true
console.log(str.startsWith("hello")); // true

c. replace()
Replace substrings.

javascript
console.log(str.replace("world", "JS")); // "hello JS"

d. trim()
Remove whitespace.

javascript
const padded = "  text  ";
console.log(padded.trim()); // "text"

3. Object Methods

a. Object.keys() / Object.values() / Object.entries()
Iterate over objects.

javascript
const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ["a", "b"]
console.log(Object.values(obj)); // [1, 2]
console.log(Object.entries(obj)); // [["a", 1], ["b", 2]]

b. Object.assign()
Merge objects.

javascript
const merged = Object.assign({}, obj, { c: 3 });
console.log(merged); // { a: 1, b: 2, c: 3 }

c. Destructuring
Extract values.

javascript
const { a, b } = obj;
console.log(a); // 1

4. Asynchronous JS

a. Promises
Handle async operations.

javascript
const fetchData = () => new Promise((resolve) => {
  setTimeout(() => resolve("Data"), 1000);
});

fetchData()
  .then(data => console.log(data)) // "Data"
  .catch(err => console.error(err));

b. async/await
Write async code synchronously.

javascript
const getData = async () => {
  const data = await fetchData();
  console.log(data); // "Data"
};

5. Common Algorithms

a. Palindrome Check

javascript
const isPalindrome = (str) => {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  return clean === clean.split("").reverse().join("");
};
console.log(isPalindrome("racecar")); // true

b. Fibonacci Sequence

javascript
const fibonacci = (n) => {
  const sequence = [0, 1];
  for (let i = 2; i <= n; i++) {
    sequence[i] = sequence[i - 1] + sequence[i - 2];
  }
  return sequence.slice(0, n + 1);
};
console.log(fibonacci(5)); // [0, 1, 1, 2, 3, 5]

c. Debounce Function
Optimize frequent events.

javascript
const debounce = (func, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), delay);
  };
};

window.addEventListener("resize", debounce(() => {
  console.log("Resize event handled!");
}, 300));

6. Advanced Concepts

a. Closures
Functions retaining access to outer scope.

javascript
const counter = () => {
  let count = 0;
  return () => ++count;
};
const increment = counter();
console.log(increment()); // 1

b. this Binding
Use bindcallapply.

javascript
const user = { name: "Alice" };
function greet() { console.log(`Hello, ${this.name}`); }

greet.call(user); // "Hello, Alice"
const boundGreet = greet.bind(user);
boundGreet(); // "Hello, Alice"

c. Memoization
Cache function results.

javascript
const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    return cache[key] || (cache[key] = fn(...args));
  };
};

const factorial = memoize(n => 
  n <= 1 ? 1 : n * factorial(n - 1)
);
console.log(factorial(5)); // 120 (cached for future calls)

Practice Tips:

  1. Understand Method Chaining:

    javascript
    const result = [1, 2, 3, 4]
      .filter(num => num % 2 === 0)
      .map(num => num * 2)
      .reduce((sum, num) => sum + num, 0);
    console.log(result); // 12 (2*2 + 4*2 = 4 + 8)
  2. Master Array Manipulation:

    • Flattening arrays (flatMap)

    • Removing duplicates ([...new Set(array)])

    • Sorting (array.sort((a, b) => a - b))

  3. Practice Problem-Solving:

    • Reverse a string without reverse().

    • Find the missing number in an array.

    • Implement Promise.all from scratch.

  4. Explore Modern Features:

    • Optional chaining (obj?.prop)

    • Nullish coalescing (value ?? defaultValue)

    • Dynamic imports (import('./module.js')

No comments:

Post a Comment

Best for you