1. How to flatten an array without using the flat() method in JavaScript?
Answer:
To flatten an array without using flat(), you can use recursion or the reduce() method to flatten nested arrays.
Solution using recursion:
function flattenArray(arr) {
let result = [];
arr.forEach(element => {
if (Array.isArray(element)) {
result = result.concat(flattenArray(element)); // Recursively flatten the array
} else {
result.push(element);
}
});
return result;
}
const nestedArray = [1, [2, [3, [4]], 5]];
console.log(flattenArray(nestedArray)); // Outputs: [1, 2, 3, 4, 5]
Solution using reduce():
function flattenArray(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []
);
}
const nestedArray = [1, [2, [3, [4]], 5]];
console.log(flattenArray(nestedArray)); // Outputs: [1, 2, 3, 4, 5]
2. What are Generators in JavaScript?
Answer:
Generators in JavaScript are functions that can be paused and resumed during execution. They are created using the function* syntax and can yield multiple values, returning an object with value and done properties.
Example:
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = myGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
Explanation:
- Each call to
next()resumes the function execution and returns the next yielded value. - When the generator finishes, it returns
{ value: undefined, done: true }.
3. What is Currying in JavaScript?
Answer:
Currying is a technique in functional programming where a function with multiple arguments is transformed into a series of functions, each accepting a single argument.
Example:
function add(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
console.log(add(1)(2)(3)); // Outputs: 6
Explanation:
- The
addfunction is curried, meaning instead of passing all arguments at once, each function call returns a new function that accepts the next argument.
4. What is the reduce() method in JavaScript?
Answer:
The reduce() method is used to iterate through an array, applying a function (called a reducer) that takes two arguments (an accumulator and the current value). It reduces the array to a single output value.
Syntax:
array.reduce((accumulator, currentValue) => {
// operation on accumulator and currentValue
}, initialValue);
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Outputs: 15
Explanation:
- The
reduce()method starts with an initial value of 0 (the second argument) and adds each element (num) to the accumulator (acc) until the array is fully iterated.
5. Map vs WeakMap in JavaScript
Answer:
- Map:
- A
Mapis a collection of key-value pairs where both the keys and values can be of any type. - Keys are strongly referenced, meaning they won’t be garbage collected even if they are no longer needed.
- It has methods like
set(),get(),has(), anddelete()to manipulate the entries. - Keys in
Mapcan be of any type (objects, strings, numbers, etc.).
Example:
const map = new Map();
const objKey = { key: 'value' };
map.set(objKey, 'someValue');
console.log(map.get(objKey)); // Outputs: 'someValue'
console.log(map.has(objKey)); // Outputs: true
map.delete(objKey); // Removes the entry
- WeakMap:
- A
WeakMapis a collection of key-value pairs where the keys must be objects and are weakly referenced. If the object reference is no longer needed, it can be garbage collected. - Keys in
WeakMapare not enumerable, meaning there is no way to retrieve all the keys or values (nokeys(),values(), orentries()methods). - Useful for cases where you want the key to be garbage collected when the object is no longer in use.
Example:
const weakMap = new WeakMap();
let objKey = { key: 'value' };
weakMap.set(objKey, 'someValue');
console.log(weakMap.get(objKey)); // Outputs: 'someValue'
objKey = null; // The object is eligible for garbage collection
// After garbage collection, the key-value pair is removed from WeakMap
Key Differences:
Mapholds strong references to keys, whereasWeakMapholds weak references.WeakMapkeys must be objects, whileMapkeys can be of any type.WeakMapdoesn’t have iteration methods likekeys(),values(), orentries()because keys are weakly referenced and could disappear due to garbage collection.
Discover more from ABWEBDEV
Subscribe to get the latest posts sent to your email.