51. How do you sort arrays?
The
sort() method is used to sort the elements of an array.Sorting Strings
const fruits = ["Banana", "Apple", "Mango"];
fruits.sort();
console.log(fruits);
Output:
["Apple", "Banana", "Mango"]Sorting Numbers
By default,
sort() converts elements to strings, so a comparison function should be used for numbers.const numbers = [10, 5, 20, 2];
numbers.sort((a, b) => a - b);
console.log(numbers);
Output:
[2, 5, 10, 20]Descending Order:
numbers.sort((a, b) => b - a);
Interview Tip:
sort() mutates the original array.52. What is array destructuring?
Array destructuring allows you to extract values from an array and assign them to variables.
Example:
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a);
console.log(b);
console.log(c);
Output:
10
20
30
Skipping Values:
const numbers = [10, 20, 30];
const [first, , third] = numbers;
console.log(first, third);
Output:
10 30
Default Values:
const numbers = [10];
const [a, b = 20] = numbers;
console.log(a, b);
Output:
10 20
53. What are Sets?
A
Set is a collection of unique values.Duplicate values are automatically removed.
Example:
const numbers = new Set([1, 2, 2, 3, 3]);
console.log(numbers);
The Set contains:
{1, 2, 3}Common Methods:
const numbers = new Set();
numbers.add(10);
numbers.add(20);
console.log(numbers.has(10));
numbers.delete(20);
Convert Set to Array:
const arr = [...numbers];
54. What are Maps?
A
Map is a collection of key-value pairs.Unlike regular objects, a
Map can use different data types as keys.Example:
const users = new Map();
users.set(1, "Deepak");
users.set(2, "John");
console.log(users.get(1));
Output:
Deepak
Common Methods:
users.set(key, value);
users.get(key);
users.has(key);
users.delete(key);
users.clear();
Example:
console.log(users.has(2));
Output:
true
Map vs Object:
Map
• Any value can be a key
• Has size property
• Built-in methods
• Designed for key-value collections
Object
• Keys are primarily strings/symbols
• No built-in size
• Different object APIs
• General-purpose objects
55. What are Symbols?
Symbol is a primitive data type used to create unique identifiers.Example:
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2);Output:
false
Even though both have the same description, each
Symbol is unique.Using Symbol as an Object Property:
const id = Symbol("id");
const user = {
name: "Deepak",
[id]: 101
};
console.log(user[id]);Common Use:
Symbols are useful when you need unique property keys that are unlikely to conflict with other properties.56. What are generators?
Generators are special functions that can pause and resume execution.
They are created using
function* and use the yield keyword.Example: