JS 2025 Flashcards
What’s the best way to clone an Object?
structuredClone(objectName)
alternative: JSON.parse(JSON.stringify(objectName) and assign to a new object (=)
How do you protect an Object from any modifications? No changes to values, no new/deleted properties?
Object.freeze(objectName)
How do you protect an Object from new/deleted properties
Object.seal(objectName)
How do you protect an Object from new properties only?
Object.preventExtensions(objectName)
How do you compare the Objects properly?
- JSON.stringify(object1) === JSON.stringify(object2)
- _.isEqual(obj1, obj2)
Objects need to be converted to strings to be compared
Iterating through an object dynamically
People often loop using for…in, but a better way is to get all Keys
console.log(Object.keys(product));
// ✅ [“name”, “specs”]
Iterating through an object dynamically
People often loop using for…in, but a better way is to get all Values
console.log(Object.values(product));
// ✅ [“Laptop”, { ram: “16GB”, storage: “512GB” }]
Iterating through an object dynamically
People often loop using for…in, but a better way is to get all Keys & Values
console.log(Object.entries(product));
// ✅ [[“name”, “Laptop”], [“specs”, { ram: “16GB”, storage: “512GB” }]]
What does the for…of loop do in JavaScript?
It loops through the values of an array without needing an index.
let numbers = [10, 20, 30];
for (let num of numbers) {
console.log(num); // Prints 10, then 20, then 30
}
What does break do inside a loop?
It stops the loop immediately when a condition is met.
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Stops the loop when i is 5
console.log(i);
}
Why use -Infinity when finding a maximum number?
-Infinity ensures any number is larger than it.
What does && do inside an if statement?
It checks two conditions at the same time.
Can multiple if statements run inside a function?
Yes! Unlike if-else, all if conditions will be checked.
splice() heuristic for how each element works
arr.splice(index, howManyToRemove, valueToInsert)