The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).
The order of the array returned by Object.entries() does not depend on how an object is defined. If there is a need for certain ordering, then the array should be sorted first, like Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));.
for-ofloop
constobject1= { a:'somestring', b:42};for (const [key,value] ofObject.entries(object1)) {console.log(`${key}: ${value}`);}// expected output:// "a: somestring"// "b: 42"// order is not guaranteed
for-in loop
constmyObject= { a:'somestring', b:42};for (const [key,value] ofObject.entries(myObject)) {for (constkeyItemin key) {console.log(key[keyItem]); // Expected: a & b }}
(function () {let randomNumbers = [];let finished;while (!finished) {constrndNumber=Math.random();randomNumbers.push(rndNumber);if (rndNumber >0.5) { finished =true;console.log(randomNumbers); } }})();// This example uses a IIFE
Question
What's the main difference between for-of and for-in loops?
Answer: for-of are used for arrays and for-in for objects
break vs return
break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.
(function () {constmyArray= [1,2,3,4,5,6];for (let i =0; i <myArray.length; i++) {if (myArray[i] ===3) {console.log('This uses return');return; } }for (let i =0; i <myArray.length; i++) {if (myArray[i] ===3) {console.log('This uses break');break; } }})();// Expected:// This uses return// This will never get to the break statement
(function () {constmyArray= [1,2,3,4,5,6];// for (let i = 0; i < myArray.length; i++) {// if (myArray[i] === 3) {// console.log('This uses return');// return;// }// }for (let i =0; i <myArray.length; i++) {if (myArray[i] ===3) {console.log('This uses break');break; } }})();// Expected result: // This uses break