. Array Methods
a. map()
Transform each element in an array.
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.
const evens = numbers.filter(num => num % 2 === 0); console.log(evens); // [2]
c. reduce()
Reduce an array to a single value.
const sum = numbers.reduce((acc, num) => acc + num, 0); console.log(sum); // 6
d. find()
/ findIndex()
Find the first match.
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.
const hasNegative = numbers.some(num => num < 0); // false const allPositive = numbers.every(num => num > 0); // true
f. flat()
Flatten nested arrays.
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.
const str = "hello world"; const words = str.split(" "); // ["hello", "world"] const newStr = words.join("-"); // "hello-world"
b. includes()
/ startsWith()
/ endsWith()
Check substrings.
console.log(str.includes("world")); // true console.log(str.startsWith("hello")); // true
c. replace()
Replace substrings.
console.log(str.replace("world", "JS")); // "hello JS"
d. trim()
Remove whitespace.
const padded = " text "; console.log(padded.trim()); // "text"
3. Object Methods
a. Object.keys()
/ Object.values()
/ Object.entries()
Iterate over objects.
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.
const merged = Object.assign({}, obj, { c: 3 }); console.log(merged); // { a: 1, b: 2, c: 3 }
c. Destructuring
Extract values.
const { a, b } = obj; console.log(a); // 1
4. Asynchronous JS
a. Promises
Handle async operations.
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.
const getData = async () => { const data = await fetchData(); console.log(data); // "Data" };
5. Common Algorithms
a. Palindrome Check
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
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.
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.
const counter = () => { let count = 0; return () => ++count; }; const increment = counter(); console.log(increment()); // 1
b. this
Binding
Use bind
, call
, apply
.
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.
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:
Understand Method Chaining:
javascriptconst 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)
Master Array Manipulation:
Flattening arrays (
flatMap
)Removing duplicates (
[...new Set(array)]
)Sorting (
array.sort((a, b) => a - b)
)
Practice Problem-Solving:
Reverse a string without
reverse()
.Find the missing number in an array.
Implement
Promise.all
from scratch.
Explore Modern Features:
Optional chaining (
obj?.prop
)Nullish coalescing (
value ?? defaultValue
)Dynamic imports (
import('./module.js')
No comments:
Post a Comment